FutureBuilder快照数据类型不正确

发布于 2025-02-06 01:05:30 字数 2094 浏览 3 评论 0原文

我正在使用flutter futurebuilder widget和sharedPreferences,在使用之前加载偏好以获取语言并将其传递给儿童窗口小部件。

这是我的代码:

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:i18n_extension/i18n_widget.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'helpers/color.dart';
import 'pages/home.dart';
import '../constants.dart';

void main() {
  runApp(
    const ProviderScope(
      child: MyApp(),
    ),
  );
}

Future<SharedPreferences> getPrefs() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs;
}

Locale getLanguageSetting(SharedPreferences prefs) {
  String? lang = prefs.getString('language');
  if (LANGUAGES.contains(lang)) {
    return Locale(lang, '');
  }
  return const Locale('en', '')
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: getPrefs(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
              return MaterialApp(
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en', ''),
        Locale('jp', ''),
      ],
      home: I18n(
          initialLocale: getLanguageSetting(snapshot.data),
          child: HomeWidget(getPrefs: snapshot.data)), // to force locale to jp
    );
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      }
    );
  }
}

但是我在snapshot.data的类型上遇到了麻烦:我将其传递给它发送的方法和小部件都将其发送回一个类型错误参数类型'对象'?无法分配到参数类型的“共享”

。 ),但似乎是类型asyncsnapshot&lt; object?&gt;

为什么?我应该铸造snapshot.data sharedPreferences type(我对铸造不太满意)吗?我该怎么做?

I am using a Flutter FutureBuilder widget and SharedPreferences, to wait for the preferences to be loaded before using them to get the language and pass them to child widgets.

Here is my code:

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:i18n_extension/i18n_widget.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'helpers/color.dart';
import 'pages/home.dart';
import '../constants.dart';

void main() {
  runApp(
    const ProviderScope(
      child: MyApp(),
    ),
  );
}

Future<SharedPreferences> getPrefs() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs;
}

Locale getLanguageSetting(SharedPreferences prefs) {
  String? lang = prefs.getString('language');
  if (LANGUAGES.contains(lang)) {
    return Locale(lang, '');
  }
  return const Locale('en', '')
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: getPrefs(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
              return MaterialApp(
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en', ''),
        Locale('jp', ''),
      ],
      home: I18n(
          initialLocale: getLanguageSetting(snapshot.data),
          child: HomeWidget(getPrefs: snapshot.data)), // to force locale to jp
    );
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      }
    );
  }
}

But I have trouble with the type of snapshot.data: both the method and widget I'm passing it to send back a type error The argument type 'Object?' can't be assigned to the parameter type 'SharedPreferences'.

I thought snapshot.data should be of type SharedPreferences according to future: getPrefs(), but it seems it's of type AsyncSnapshot<Object?>.

Why? Should I cast snapshot.data into a SharedPreferences type (I'm not very comfortable with casting)? How can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

飘落散花 2025-02-13 01:05:30

将快照中的类型定义为asyncsnapshot&lt; sharedPreferences&gt;快照。然后,如果您正在运行NULL安全版本,则将共享Preferences的类型更改为共享流程吗?在getlanguagesetting中。

    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';

    void main() {
      runApp(MyApp());
    }

    Future<SharedPreferences> getPrefs() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      return prefs;
    }

    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);

      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: getPrefs(),
            builder: (context, AsyncSnapshot<SharedPreferences?> snapshot) {
              if (snapshot.hasData) {
                print(snapshot.data.runtimeType);
                getLanguageSetting(snapshot.data);
                return MaterialApp(
                    localizationsDelegates: const [],
                    supportedLocales: const [
                      Locale('en', ''),
                      Locale('jp', ''),
                    ],
                    home: Container(
                      color: Colors.red,
                    ));
              } else {
                return const Center(
                  child: CircularProgressIndicator(),
                );
              }
            });
      }
    }

    void getLanguageSetting(SharedPreferences? prefs) {
      print(prefs.runtimeType);
    }


Define the type in snapshot as AsyncSnapshot<SharedPreferences> snapshot. Then If you are running a null safe version change the type of sharedPreferences to SharedPreferences? in getLanguageSetting also.

    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';

    void main() {
      runApp(MyApp());
    }

    Future<SharedPreferences> getPrefs() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      return prefs;
    }

    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);

      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: getPrefs(),
            builder: (context, AsyncSnapshot<SharedPreferences?> snapshot) {
              if (snapshot.hasData) {
                print(snapshot.data.runtimeType);
                getLanguageSetting(snapshot.data);
                return MaterialApp(
                    localizationsDelegates: const [],
                    supportedLocales: const [
                      Locale('en', ''),
                      Locale('jp', ''),
                    ],
                    home: Container(
                      color: Colors.red,
                    ));
              } else {
                return const Center(
                  child: CircularProgressIndicator(),
                );
              }
            });
      }
    }

    void getLanguageSetting(SharedPreferences? prefs) {
      print(prefs.runtimeType);
    }


~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文