dart Flutter定位:对空值使用了空检查运算符

bvhaajcl  于 2023-02-27  发布在  Flutter
关注(0)|答案(1)|浏览(142)

我不知道为什么Flutter定位代码不工作与零安全。
当我检查值时,我总是得到用于空值的空检查操作符。
getTranslated导致错误。
main.dart

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    List<Locale> _locals = [];
    AppConstants.languages.forEach((language) {
      _locals.add(Locale(language.languageCode, language.countryCode));
    });

    return MaterialApp(
      title: AppConstants.APP_NAME,
      navigatorKey: MyApp.navigatorKey,
      debugShowCheckedModeBanner: false,
      theme: Provider.of<ThemeProvider>(context).darkTheme ? dark : light,
      locale: Provider.of<LocalizationProvider>(context).locale,
      localeResolutionCallback: (locale, supportedLocales) {
        for (var supportedLocale in supportedLocales)
        {
          if(supportedLocale.languageCode == locale?.languageCode|| supportedLocale.countryCode == locale?.countryCode)
          {
            return supportedLocale;
          } 
        }
        return supportedLocales.first;
      },
      localizationsDelegates:  [
        AppLocalization.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: _locals,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Material App Bar'),
        ),
        body:  Center(
          child: Text(getTranslated("hi", context)!,),
        ),
      ),
    );
  }
}

获取已翻译
此方法无法返回任何值。

String? getTranslated(String key, BuildContext context) {
  return AppLocalization.of(context)?.translate(key);
}

应用程序_本地化.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../utils/app_constants.dart';

class AppLocalization {
  AppLocalization(this.locale);

late Locale locale;

  static AppLocalization? of(BuildContext context) {
    return Localizations.of<AppLocalization>(context, AppLocalization);
  }

late Map<String, String> _localizedValues;

  Future<void> load() async {
    String jsonStringValues = await rootBundle
        .loadString('assets/languages/${locale.languageCode}.json');
    Map<String, dynamic> mappedJson = json.decode(jsonStringValues);
    _localizedValues =
        mappedJson.map((key, value) => MapEntry(key, value.toString()));

        print("inside app loca: $_localizedValues");
  }

  String translate(String key) {
    return _localizedValues[key]!;
  }

  static const LocalizationsDelegate<AppLocalization> delegate =
      _DemoLocalizationsDelegate();
}

class _DemoLocalizationsDelegate
    extends LocalizationsDelegate<AppLocalization> {
  const _DemoLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    List<String> _languageString = [];
    AppConstants.languages.forEach((language) {
      _languageString.add(language.languageCode);
    });
    return _languageString.contains(locale.languageCode);
  }

  @override
  Future<AppLocalization> load(Locale locale) async {
    AppLocalization localization = AppLocalization(locale);
    await localization.load();
    return localization;
  }

  @override
  bool shouldReload(LocalizationsDelegate<AppLocalization> old) => false;
}

应用程序本地化代码处理语言数据。
错误堆栈为

The following _CastError was thrown building MyApp(dirty, dependencies:
[_InheritedProviderScope<LocalizationProvider>, _InheritedProviderScope<ThemeProvider>], state:
_MyAppState#522f6):
Null check operator used on a null value

The relevant error-causing widget was:
  MyApp MyApp:file:///D:/1npcheck/np3/lib/main.dart:28:18

When the exception was thrown, this was the stack:
#0      _MyAppState.build (package:np_3/main.dart:77:51)
#1      StatefulElement.build (package:flutter/src/widgets/framework.dart:4992:27)
#2      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4878:15)
#3      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5050:11)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
avwztpqn

avwztpqn1#

load()是一个未来方法,它将需要一些帧来分配数据。代替空Assert,您可以在空情况下提供默认值,而这只是字符串情况。

String translate(String key) {
    return _localizedValues[key]??"still empty";
  }

还有

Text(getTranslated("hi", context)?? "loading",),

查找更多关于null-safety的信息,也可以查看FutureBuilder-class来处理将来的方法。

相关问题