如何修复Shared Preferences在Flutter中返回空字符串?

问题描述

我正在使用共享的首选项Flutter中存储和加载地图的值,但出现错误

The following assertion was thrown building UserPro(dirty):
A non-null String must be provided to a Text widget.
'package:Flutter/src/widgets/text.dart':
Failed assertion: line 360 pos 10: 'data != null'

我当然知道 Shared Preferences返回一个空字符串值,但是我不知道为什么,因为我正在等待该值。以及如何解决。我附有此问题的代码供您参考

----存储------

void setUserValues() async{
    SharedPreferences sharedPrefs = await SharedPreferences.getInstance();
    currentUser.forEach((k,v)=>sharedPrefs.setString(k,v));
  }

此处 currentUser 包含包含用户数据(例如“名称”,“电子邮件”等)的地图。

----加载------

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

SharedPreferences localStorage;


class UserPro extends StatelessWidget{
  final currentUser;

  String name;
  UserPro({this.currentUser}){
    name=localStorage.getString("Name");;
  }
  static Future init() async{
    localStorage = await SharedPreferences.getInstance();
  }
  @override
  Widget build(BuildContext context) {
    // Todo: implement build
    return Scaffold(
      body: Center(
        child: Text(
            name,style: TextStyle(
              fontSize: 15,fontFamily: 'Berlin Sans FB',fontWeight: FontWeight.bold,),);
  }
}

解决方法

使用FutureBuilder

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

//SharedPreferences localStorage;


class UserPro extends StatelessWidget{
  final currentUser;

  //String name;
  UserPro({this.currentUser});
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Center(
        child: FutureBuilder<SharedPreferences>(
             future: SharedPreferences.getInstance(),builder: (context,snapshot){
                if (!snapshot.hasData) {
                   return CircularProgressIndicator();
                  }
            return Text(
            snapshot.data.getString("name"),style: TextStyle(
              fontSize: 15,fontFamily: 'Berlin Sans FB',fontWeight: FontWeight.bold,),},);
  }
}