【问题标题】:Using Flutter and Dart, how can I get this Future to work?使用 Flutter 和 Dart,我怎样才能让这个 Future 工作?
【发布时间】:2019-11-08 10:38:07
【问题描述】:

我知道还有其他方法可以实现这一点,但我想通过 initState() 使用 Future 来使用 SharedPreferences 获取列表。下面说明了我想要实现的目标,但它没有按要求工作,因为 Future 在完成任务之前立即返回。

这应该如何构建?


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

class _MyHomePageState extends State<MyHomePage> {
  SharedPreferences _prefs;
  String _sMessage = "No response from getting params";
  List<String> _lsCategories;

  @override
  void initState() {
    super.initState();
    _initPreferences().then((_) {
      try {
        _lsCategories = _prefs.getStringList("categories") ?? [];
        debugPrint("Categories = $_lsCategories");
        _sMessage = "Categories loaded OK";
      } catch (vError) {
        _sMessage = ("Error loading categories = $vError");
      }
      setState(() {});
    });
  }

  Future<void> _initPreferences() async {
    SharedPreferences.getInstance().then((prefs) {
      _prefs = prefs;
      debugPrint("Preferences initialized OK");
    }).catchError((vError) {
      debugPrint("Error initializing preferences = ${vError.toString()}");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(_sMessage,
                style: TextStyle(
                    color: Colors.red[500],
                    fontWeight: FontWeight.bold,
                    fontSize: 20)),
          ],
        ),
      ),
    );
  }
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Future Test',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: "Flutter Future Test"),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}


【问题讨论】:

  • 你的_initPreferences 方法没有返回任何Future

标签: flutter dart future


【解决方案1】:

试试看。

Future<void> _initPreferences() async {
    _prefs = await SharedPreferences.getInstance().catchError((vError) { 
          debugPrint("Error initializing preferences = ${vError.toString()}");
    };
    debugPrint("Preferences initialized OK");
}

【讨论】:

    【解决方案2】:

    将您的 _initPreferences 方法更改为以下内容:

    Future<void> _initPreferences() async {
      try {
        final prefs = await SharedPreferences.getInstance();
        _prefs = prefs;
        debugPrint("Preferences initialized OK");
      } catch (e) {
        debugPrint("Error initializing preferences = ${e.toString()}");
      }
    }
    

    问题在于,在 Future 上使用 .then() 时,您不会等待该未来完成,使用 await 确实会等待。

    【讨论】:

    • 不是真的,await 与使用 then 是一样的——我的意思是你可以通过使用 awaitthen 来获得相同的结果
    • 不是真的,await 暂停执行 then 没有。很好的解释:stackoverflow.com/a/54515559/5608661
    • 您可以使用awaitthen 获得相同的结果 - await 只不过是“语法糖” - 基本上 OP 不会从 _initPreferences 方法返回正确的 Future
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    相关资源
    最近更新 更多