颤振中的提供者不会改变屏幕

时间:2021-04-02 22:07:12

标签: flutter dart flutter-provider

我在 Flutter 应用程序中使用提供程序来更改我的应用程序中的屏幕。这是我的 main.dart 文件:

{A, B, E}

这也是我的 wrapper.dart 文件,屏幕选择:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:school_app/services/auth_service.dart';
import 'package:school_app/wrapper.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AuthService().auth,
      child: MaterialApp(
        home: Wrapper(),
      ),
    );
  }
}

这是我的 AuthProvider 类:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:school_app/screens/authenticate/auth.dart';
import 'package:school_app/models/user.dart';
import 'package:school_app/screens/school/home.dart';
import 'package:school_app/services/auth_service.dart';

class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = Provider.of<AuthProvider>(context); 
    print(user.auth);
    if(!user.auth) return Auth();
    return Home();
  }
}

我也制作了 Wrapper 小部件的这个变体,但它也不起作用:

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

class AuthService {


   /* AuthUser _user(User user) {
    return user != null ? AuthUser(uid: user.uid) : null;
  }*/

AuthProvider auth = new AuthProvider();

  //sign in
  Future signIn(String username, String password) async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      var dio = Dio();
      Response user = await dio.post('url', data: {
        'username': username,
        'password': password
      });
      if(user.data['success'] == false) return user.data['msg'];
      await prefs.setString('token', user.data['token']);
      auth.setAuth(true);
      print("SUCCESS");
    } catch(e) {
      print('Error ' + e.toString());
    }
  }

}

class AuthProvider with ChangeNotifier {
  bool _auth;

  AuthProvider() {
    _auth = false;
  }

  bool get auth => _auth;

  void setAuth(bool auth) {
    _auth = auth;
    notifyListeners();
  }
}

还有这个:

class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = context.watch<AuthProvider>();
    print(user.auth);
    if(!user.auth) return Auth();
    return Home();
  }
}

当我在 AuthProvider 类 setAuth 中调用一个函数时,没有任何改变。你能帮我找出我的错误吗?

0 个答案:

没有答案