首页 > 解决方案 > 尝试调用我的 getter 时,我得到了 Invalid argument(s)

问题描述

我有这个类class InitDrawer extends StatelessWidget,在构建方法中我有这行代码

final _auth = Provider.of<Auth>(context);
final drawerHeader = UserAccountsDrawerHeader(accountName: Text(_auth.name), ...);

但是当我尝试调用 getter时,name我收到了这个错误

无效参数

在我的提供者里面我有这个代码

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

import '../models/http_exception.dart';

class Auth with ChangeNotifier {
  String _token;
  DateTime _expiryDate;
  int _userId;
  int _carId;
  String _email;
  String _name;
  Timer _authTimer;

  bool get isAuth {
    return token != null;
  }

  String get token {
    if (_expiryDate != null &&
        _expiryDate.isAfter(DateTime.now()) &&
        _token != null) {
      return _token;
    }
    return null;
  }

  String get name {
    if (_name == null) {
      return null;
    }
    return _name;
  }

  String get email {
    return _email;
  }

  int get carId {
    return _carId;
  }

  Future<void> _authenticate(String email, String password, String auth,
      [String name]) async {
    const url = 'someurl';
    try {
      final response = await http.post(
        url,
        body: json.encode({
          'auth': auth,
          'email': email,
          'password': password,
          'name': name,
        }),
      );
      final Map<String, dynamic> responseData = json.decode(response.body);
      if (responseData['error'] != null) {
        throw HttpException(responseData['error']['message']);
      }
      DateTime date = DateTime.now().add(
        Duration(
          seconds: int.parse(
            responseData['expiresIn'],
          ),
        ),
      );
      _token = responseData['idToken'];
      _userId = int.parse(responseData['localId']);
      _carId = int.parse(responseData['carID']);
      _name = responseData['name'];
      _email = responseData['email'];
      _expiryDate = date;
      _autoLogout();
      notifyListeners();
      // store token to device
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      final userData = json.encode({
        'token': _token,
        'userId': _userId,
        'expiryDate': _expiryDate.toIso8601String(),
      });
      prefs.setString('userData', userData);
    } catch (error) {
      throw error;
    }
  }

  Future<void> signup(String email, String password, String name) async {
    return _authenticate(email, password, 'signup', name);
  }

  Future<void> signin(String email, String password) async {
    return _authenticate(email, password, 'signin', null);
  }
}

这是我的 InitDrawer

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:release/providers/auth.dart';

class InitDrawer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserAccountsDrawerHeader drawDrawer(Auth auth) {
      return UserAccountsDrawerHeader(
        accountName: Text(auth.name), // here i get the error!!!
        accountEmail: Text(auth.email),
        currentAccountPicture: CircleAvatar(
          child: FlutterLogo(size: 42.0),
          backgroundColor: Colors.white,
        ),
      );
    }

    return Container(
      child: Consumer<Auth>(
        builder: (context, auth, child) => ListView(
          children: <Widget>[
            drawDrawer(auth),
            ListTile(
              title: Text('To page 1'),
              onTap: () => {},
            ),
            ListTile(
              title: Text('To page 2'),
              onTap: () => {},
              onTap: () => Navigator.of(context).push(_NewPage(2)),
            ),
            ListTile(
              title: Text('other drawer item'),
              onTap: () {},
            ),
          ],
        ),
      ),
    );
  }
}

标签: flutterdart

解决方案


推荐阅读