使用Flutter和Dart,如何使Future正常工作?

时间:2019-06-26 13:06:10

标签: flutter dart future

我知道还有其他方法可以实现此目的,但是我想通过initState()使用Future来使用SharedPreferences获得List。以下内容说明了我想要实现的目标,但由于需要在完成任务之前立即返回,因此无法按要求工作。

应如何组织?


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();
}


2 个答案:

答案 0 :(得分:1)

将您的Future<void> _initPreferences() async { _prefs = await SharedPreferences.getInstance().catchError((vError) { debugPrint("Error initializing preferences = ${vError.toString()}"); }; debugPrint("Preferences initialized OK"); } 方法更改为以下内容:

_initPreferences

问题是,当在Future上使用Future<void> _initPreferences() async { try { final prefs = await SharedPreferences.getInstance(); _prefs = prefs; debugPrint("Preferences initialized OK"); } catch (e) { debugPrint("Error initializing preferences = ${e.toString()}"); } } 时,您并没有等待该将来完成,而是使用.then()会等待。

答案 1 :(得分:0)

尝试一下。

$excluded_user='1,2,3';