1

只是我的任务是给变量“type”一个共享数据,请帮帮我

*此示例代码是 main.dart,我使用共享首选项进行数据传输,类型的键是“typeOfUser”,我看到了很多博客甚至 stackoverflow,但没有一个适合我 *

代码如下:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:nativestore/database/datatrans.dart';
import 'package:nativestore/homepage.dart';
import 'package:nativestore/loginout/loginpage.dart';
import 'package:nativestore/shophomepage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'loginout/auth.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: routePage(),
    );
  }
}

class routePage extends StatefulWidget {
  @override
  routePageState createState() => routePageState();
}

class routePageState extends State<routePage> {
  final AuthService _auth = AuthService();
  int type;
  bool isLoggedin = false;
  getIntValuesSF() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int val = prefs.getInt('typeOfUser');
    return val;
  }

  @override
  void initState() {
    super.initState();
    print("type-->${getIntValuesSF()}");
    print("Init state");
    _auth.autoLogin().then((value) {
      if (value == 'null') {
        print(isLoggedin);
        setState(() {
          isLoggedin = false;
        });
      } else if (value != null) {
        setState(() {
          isLoggedin = true;
        });
      } else {
        setState(() {
          isLoggedin = false;
        });
      }
    });
  }

  // var Utype = GetUserType(type:"ko")
  @override
  Widget build(BuildContext context) {
    return isLoggedin == true
        ? (type == 2)
            ? homePage()
            : ShopHomePage()
        : loginPage();
  }
}

输出 :

Performing hot restart...
Syncing files to device Redmi Note 8...
Restarted application in 2,645ms.
I/flutter (14262): type-->Instance of 'Future<dynamic>'
I/flutter (14262): Init state

所以请帮助我。提前致谢...

4

2 回答 2

3

您的代码打印的原因Instance of 'Future<dynamic>'是因为正在打印的实例getIntValuesSF()而不是它返回的值。你可以在这里做的是运行 async 函数并then在未来完成时使用它来获取它的返回值。

void initState() {
    super.initState();
    getIntValuesSF().then((value) {
        debugPrint('type-->$value');
        // do functions requiring value parameter
    });
}
于 2021-04-23T11:42:22.773 回答
0

更改:

print("type-->${getIntValuesSF()}");

到:

var value = await getIntValuesSF();
print("type-->${value.toString()}");
于 2021-04-23T10:48:58.880 回答