Flutter-在应用启动时发出http发布请求,并使响应可响应下一个api调用

时间:2019-02-04 14:03:07

标签: android http post dart flutter

我需要进行http发布以对api进行身份验证才能获得身份验证。我创建了用于登录请求的类(目前仍为值编码):

class AuthDevice {
  final String deviceId = '1234567890';
  final String apiKey = 'my_key';
}

响应类别:

class AuthDeviceResponse {
  final String tokenType;
  final String accessToken;


  AuthDeviceResponse({this.tokenType, this.accessToken});

  factory AuthDeviceResponse.fromJson(Map<String, dynamic> json) {
    return AuthDeviceResponse(
      tokenType: json['userId'],
      accessToken: json['id']
    );
  }
}

最后,用于修改实际登录信息的方法:

Future<AuthDeviceResponse> authDevice() async {
  final response =
  await http.post('https://url',
      headers: {HttpHeaders.acceptHeader: "application/json"},
  body: jsonEncode(new AuthDevice()));

  if (response.statusCode == 200) {

    return AuthDeviceResponse.fromJson(json.decode(response.body));
  } else {

    throw Exception('Failed auth');
  }
}

现在,我想在应用启动后立即自动调用authDevice方法,等待登录,将auth标头保存为全局变量,并将其用于所有其他api调用。我的main.dart:

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

class MyApp extends StatelessWidget {

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'NavigationDrawer Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new HomePage(),
    );
  }
}

主页包含导航抽屉:

class HomePage extends StatefulWidget {
  final drawerItems = [
    new DrawerItem("Item1", Icons.list),
    new DrawerItem("Item2", Icons.event_note),
    new DrawerItem("Item3", Icons.info_outline),
    new DrawerItem("Item4", Icons.account_balance)
  ];

  @override
  State<StatefulWidget> createState() {
    return new HomePageState();
  }
}

class HomePageState extends State<HomePage> {
  int _selectedDrawerIndex = 0;

  _getDrawerItemWidget(int pos) {
    switch (pos) {
      case 0:
        return new FirstFragment();
      case 1:
        return new ThirdFragment();
      case 2:
        return new ThirdFragment();
      case 3:
        return new CitiesListFragment();

      default:
        return new Text("Error");
    }
  }
 //... rest of code to create drawer laout

因此,主窗口会自动选择第一个抽屉项目并显示FirstFragment。在此之前,我要进行身份验证。如何在显示主窗口之前拨打电话并等待验证?

0 个答案:

没有答案