【问题标题】:Flutter sharedPreferences initializationFlutter sharedPreferences 初始化
【发布时间】:2021-08-02 21:36:18
【问题描述】:

我想在加载应用程序之前初始化我的 sharedPref 对象。我尝试了 init func 等,但总是在屏幕上出现“未来的实例”文本然后我的 sharedPref 对象初始化结束然后正确执行 getStringList 方法。我的意思是我不不想看到“未来的实例”。我该怎么办?

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  _MyHomePageState().createSharedObject();
  runApp(
    MyApp(),
  );
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    _MyHomePageState().createSharedObject();
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String baslik, mesaj;

  List<String> kaydedilenNotlar = [];
  List<String> kaydedilenBasliklar = [];
  List<String> deneme = [];
  SharedPreferences sharedPreferences;

  Future createSharedObject() async {
    sharedPreferences = await SharedPreferences.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            showDialog(
                context: context,
                builder: (context) {
                  return AlertDialog(
                    backgroundColor: Colors.yellowAccent[100],
                    title: Text(
                      "Yeni Not",
                      textAlign: TextAlign.center,
                    ),
                    content: Container(
                      height: 250,
                      child: Column(
                        children: [
                          Expanded(
                            child: TextField(
                              onChanged: (value) {
                                setState(() {
                                  baslik = value;
                                });
                              },
                              decoration: InputDecoration(
                                border: OutlineInputBorder(),
                                hintText: "Başlık",
                                hintStyle: TextStyle(
                                    color: Colors.black,
                                    fontStyle: FontStyle.italic),
                              ),
                            ),
                          ),
                          TextField(
                            onChanged: (value) {
                              setState(() {
                                mesaj = value;
                              });
                            },
                            maxLines: 5,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(),
                              hintText: "Not",
                            ),
                          ),
                          TextButton(
                              onPressed: () async {
                                kaydedilenNotlar.add(mesaj);
                                kaydedilenBasliklar.add(baslik);

                                sharedPreferences =
                                    await SharedPreferences.getInstance();
                                /* sharedPreferences.setStringList(
                                    "not", kaydedilenNotlar);
                                sharedPreferences.setStringList(
                                    "baslik", kaydedilenBasliklar);*/
                              },
                              child: Text(
                                "Kaydet",
                                style: TextStyle(fontSize: 18),
                              ))
                        ],
                      ),
                    ),
                  );
                });
          },
        ),
        appBar: AppBar(
          centerTitle: true,
          title: Text("AJANDA"),
          bottom: TabBar(
            tabs: [
              Tab(
                child: Text("Yapılacak"),
              ),
              Tab(
                child: Text("Yapılıyor"),
              ),
              Tab(
                child: Text("Yapıldı"),
              )
            ],
          ),
        ),
        body: TabBarView(
          children: [
            Center(
                child: Text(
                    "${sharedPreferences == null ? createSharedObject() : sharedPreferences.getStringList("not")}")),
            Center(child: Text("2. sayfa")),
            Center(child: Text("3. sayfa")),
          ],
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    原因是您的createSharedObject() 函数是Future。并在行中

     child: Text("${sharedPreferences == null ? createSharedObject() : sharedPreferences.getStringList("not")}")),
    

    您正在使用该 Future 值,而不是等待它。

    因此,如果您想等待实际值,则需要FutureBuilder

    FutureBuilder<String>(
            future: your_future_function,
            builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                if (snapshot.connectionState==ConnectionState.done){
                    return  Text(snapshot.data);
                } else {
                    return  Text('Loading');
                }
            });
    

    我必须说我认为有更好的方法来处理从 SharedPreferences 加载值,但为了简单起见,上面的解决方案应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-01
      • 2021-10-28
      • 1970-01-01
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      相关资源
      最近更新 更多