微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flutter Provider Notifylistener 未按预期工作

如何解决Flutter Provider Notifylistener 未按预期工作

我正在构建一个带有 Flutter 和 provider 包的登录系统。

我已经构建了一个用于登录注册的小型 API。

这是我的 main.dart

import path from 'path';
import express from 'express';
import multer from 'multer';

const router = express.Router();

const storage = multer.diskStorage({
  destination(req,file,cb) {
    cb(null,'uploads');
  },filename(req,cb) {
    cb(
      null,`${file.fieldname}-${Date.Now()}${path.extname(file.originalname)}`
    );
  },});

function checkFileType(file,cb) {
  const filetypes = /jpg|jpeg|png/;
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = filetypes.test(file.mimetype);

  if (extname && mimetype) {
    return cb(null,true);
  } else {
    cb('Images only!');
  }
}

const upload = multer({
  storage,fileFilter: function (req,cb) {
    checkFileType(file,cb);
  },});

router.post('/',upload.single('image'),(req,res) => {
  console.log(req.file);
  try {
    res.status(200).json({ msg: 'image uploaded successfully' });
  } catch (error) {
    console.error(error.message);
  }
  // res.send(`/${req.file.path}`);
});

export default router;

在 Auth Provider 中具有登录注册自动记录功能和 isLoggedIn 变量。

import 'package:Flutter/material.dart';
import 'package:lovely_seconds/providers/auth_provider.dart';
import 'package:lovely_seconds/screens/login_screen.dart';
import 'package:lovely_seconds/screens/shop_screen.dart';
import 'package:provider/provider.dart';


void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  runApp(MyApp());
}


class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (ctx)=>AuthProvider()),ChangeNotifierProvider(create: (ctx)=>ChatProvider()),ChangeNotifierProvider(create: (ctx)=>ThemeModeProvider()),ChangeNotifierProvider(create: (ctx)=>ConnectionProvider()),//ChangeNotifierProvider(create: (ctx)=>LogsProvider()),ChangeNotifierProxyProvider<AuthProvider,LogsProvider>(
          create: (ctx) => LogsProvider(),update: (_,auth,prevIoUs) => prevIoUs..incomingDataFromMain(auth.token,prevIoUs.logs == null ? [] : prevIoUs.logs),),],child:  Consumer<AuthProvider>(
        builder: (ctx,_){
          // print('material app build ' +auth.token);
            return MaterialApp(
              title: 'Flutter Demo',darkTheme: ThemeData.dark().copyWith(
                textTheme: ThemeData.dark().textTheme.apply(
                  fontFamily: 'Poppins',primaryTextTheme: ThemeData.dark().textTheme.apply(
                  fontFamily: 'Poppins',accentTextTheme: ThemeData.dark().textTheme.apply(
                  fontFamily: 'Poppins',theme: ThemeData(fontFamily: 'Poppins'),// themeMode: theme.isDarkMode ? ThemeMode.dark : ThemeMode.light,home: auth.isLoggedIn == true
                  ? ShopScreen()
                  : FutureBuilder(
                future: auth.autoLogin(),builder: (ctx,AsyncSnapshot snapshot){
                    if(snapshot.connectionState == ConnectionState.waiting){
                      return Center(child: CircularProgressIndicator(),);
                    }
                    else{
                      return LoginScreen();
                    }
              })
          );
        },)
    );
  }
}

在上面的函数中 isLoggedIn 设置为 true 并且我正在调用通知侦听器所以我的应用程序应该重建并且新页面应该是 ShopScreen 对吗?在商店屏幕构建方法中,我添加一个小打印语句,它是有效的,但我仍然在登录屏幕,屏幕永不改变但商店页面加载(打印语句有效)。 那么我在这里错过了什么?假设从共享首选项和 API 调用获取数据工作正常。

这是我的登录 fn。

Future<bool> autoLogin() async {
    print('auto logging running');
    var tok;
    SharedPreferences prefs = await SharedPreferences.getInstance();

    if(!prefs.containsKey('lovelydata')){
      print('no data in shared preference');
      return false;
    }
    tok = json.decode(prefs.getString('lovelydata')) as Map<String,Object>;
    this.token = tok['token'];
    print('token set by auto login fn '+token);
    isLoggedIn = true;
    this.loggedInAppUser = AppUser.fromJson(tok['AppUser']);
    notifyListeners();
    return true;
  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。