0

On trying to pass a Future-Map to the future builder widget , it gives the error below.

The JsonMap has been cast to a Future-Map using the cast-as operator and the value has been returned using Future.value(),but the below error still persists.

More details:
The builder is supposed to get these initial values , if the values in sharedpreferences are not initialized.

However on passing the Mapped intial values , Flutter treats the returned _JsonMap not as a Future-Map and gives the error below.

How to convert _JsonMap to Future-Map ?

Error:

Expected a value of type 'Future<Map<dynamic, dynamic>>?', but got one of type '_JsonMap'

Code:

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

class User{
  String name;
  int age;
  bool subscribed;

  User({this.name, this.age, this.subscribed});
}


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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'JsonMap',
      theme: ThemeData.dark(),

      home: Scaffold(


        appBar: AppBar(
          title: Text(
            'SharedPreferences returns null values',
            style: TextStyle(),
          ),
        ),
        body: UserScreen1(),
        // body: UserScreen1( sessionDataScreen1 : _sessionDataMain ),
      ),
    );
  }
}
class UserScreen1 extends StatefulWidget {
  @override
  _UserScreen1State createState() => _UserScreen1State();
}

class _UserScreen1State extends State<UserScreen1> {

  =

    User _user = User();
    var _mapGet;
     var _mapSet;


    final _formKey = GlobalKey<FormState>();


    Future<Map<dynamic, dynamic>> _getSharedPreferences (_userDataKey)  async {



      var  _userJsonInitial = '''{
        "name" : "Mock",
         "age" : 20,
         "subscribed" : true}''';


      final prefs =   await SharedPreferences.getInstance();
      final rawJsonGet =  prefs.getString(_userDataKey) ?? _userJsonInitial;
      _mapGet = await jsonDecode(rawJsonGet) as Future<Map<dynamic,dynamic>>;
      print('_mapGet = $_mapGet ');


      _mapGet.forEach((k, v) => print('${k}: ${v}'));



    // return   Future<Map<String, dynamic>>.from(json.decode(rawJsonGet));

      return Future.value(_mapGet);

   }



  void initState() {
    super.initState();

    _mapGet =   _getSharedPreferences ('_userDataKey');
    _mapGet.then((_mapGet){
    setState(() {
      _user =  User(name : _mapGet['name'], age : _mapGet['age'], subscribed : _mapGet['subscribed']);
      print(' User InitState : name = ${_user.name}, age = ${_user.age},subscribed = ${_user.subscribed},');
    });});

    }



  @override
  Widget build(BuildContext context) {
    return Column(
        mainAxisAlignment: MainAxisAlignment.center ,
        children: [
          Container(child:FutureBuilder<Map>(
          future: _mapGet,
          builder: (BuildContext context, AsyncSnapshot<Map> snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.waiting:
                return const CircularProgressIndicator();
              default:
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                } else {
                  // return  Text(' User (BuildContext) : name = ${snapshot.data.['name']}, age = ${snapshot.data['age']},subscribed = ${snapshot.data['subscribed']},');
                  return  Text(' User (BuildContext) : nameMap = ${snapshot.data} , nameUser = ${_user.name},');

                }
            }
          })),

    

    ]
    );
  }}
srt111
  • 1,079
  • 11
  • 20

0 Answers0