簡體   English   中英

我如何在flutter中將變量id傳遞給另一個頁面

[英]How can i pass variable id to another page in flutter

大家好,我有兩個頁面,我想在第二個屏幕中使用變量“id”

我該做什么 ?

屏幕一:這是用戶輸入登錄名和密碼的登錄屏幕,然后我得到所有訂單列表,然后我需要選擇 ID 並在第二個屏幕中使用它

屏幕二:我按 id 顯示該用戶的訂單

注意:我通過 api 獲取所有數據

屏幕一:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'order_list_screen.dart';

    class LoginPage extends StatefulWidget {
      @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  bool _isLoading = false;

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light.copyWith(statusBarColor: 
Colors.transparent));
    return Scaffold(
      body: Container(
       decoration: BoxDecoration(
         gradient: LinearGradient(
              colors: [Colors.blue, Colors.teal],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter),
        ),
        child: _isLoading ? Center(child: CircularProgressIndicator()) : ListView(
          children: <Widget>[
           headerSection(),
           textSection(),
           buttonSection(),
         ],
       ),
     ),
   );
 }

 signIn(String login, pass) async {
   SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
   Map data = {
     'login': login,
     'password': pass,
   };
    var jsonResponse = null;
    var response = await http.post("https://api/ws/v4/Delivery/login.php", body: data);

    if(response.statusCode == 200) {
      jsonResponse = json.decode(response.body);
      print(jsonResponse);
      jsonResponse['token']="isLoged";
  if(jsonResponse != null) {
    setState(() {
      _isLoading = false;
    });
    sharedPreferences.setString("token", jsonResponse['livreur']['nom']);
    sharedPreferences.setInt("idliv", jsonResponse['livreur']['id']);



    Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => 
 OrderListScreen()), (Route<dynamic> route) => false);


    
    
  }
}
else {
  setState(() {
    _isLoading = false;
  });
  print(response.body);
}

}

 Container buttonSection() {
  return Container(
  width: MediaQuery.of(context).size.width,
  height: 40.0,
  padding: EdgeInsets.symmetric(horizontal: 15.0),
  margin: EdgeInsets.only(top: 15.0),
  child: RaisedButton(
    onPressed: loginController.text == "" || passwordController.text == "" ? null : () {
      setState(() {
        _isLoading = true;
      });
      signIn(loginController.text, passwordController.text);
    },
    elevation: 0.0,
    color: Colors.purple,
    child: Text("Sign In", style: TextStyle(color: Colors.white70)),
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
  ),
);
 }

   final TextEditingController loginController = new TextEditingController();
    final TextEditingController passwordController = new TextEditingController();

   Container textSection() {
   return Container(
    padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0),
    child: Column(
    children: <Widget>[
      TextFormField(
        controller: loginController,
        cursorColor: Colors.white,

        style: TextStyle(color: Colors.white70),
        decoration: InputDecoration(
          icon: Icon(Icons.person, color: Colors.white70),
          hintText: "Email",
          border: UnderlineInputBorder(borderSide: BorderSide(color: Colors.white70)),
          hintStyle: TextStyle(color: Colors.white70),
        ),
      ),
      SizedBox(height: 30.0),
      TextFormField(
        controller: passwordController,
        cursorColor: Colors.white,
        obscureText: true,
        style: TextStyle(color: Colors.white70),
        decoration: InputDecoration(
          icon: Icon(Icons.lock, color: Colors.white70),
          hintText: "Password",
          border: UnderlineInputBorder(borderSide: BorderSide(color: Colors.white70)),
          hintStyle: TextStyle(color: Colors.white70),
        ),
      ),
    ],
  ),
);
 }

 Container headerSection() {
return Container(
  margin: EdgeInsets.only(top: 50.0),
  padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 30.0),
  child: Text("Code Land",
      style: TextStyle(
          color: Colors.white70,
          fontSize: 40.0,
          fontWeight: FontWeight.bold)),
   );
  }
  }

畫面二:

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:deliveryman/screens/login_screen.dart';





  Future<OrderListData> fetchOrderListData() async {
   final response = await http.post(
   'https://api/ws/v3/Delivery/orders.php',
   body: {'livreurID': '1'});

  if (response.statusCode == 200) {
   // If the server did return a 200 OK response,
   // then parse the JSON.
   return OrderListData.fromJson(json.decode(response.body));
  } else {
   // If the server did not return a 200 OK response,
   // then throw an exception.
   throw Exception('Failed to load album');
 }
}

class OrderListData {
 final orderID;
 final orderDate;
 final deliveryWishedTime;
 final deliveryTime;
 final deliveryZone;
 final clientFirstName;
 final clientLastName;
 final restoName;
 final restoImagePath;
 final nbrProduct;
 final status;
 final latitude;
 final longitude;

 OrderListData({
 this.orderID,
  this.orderDate,
   this.deliveryWishedTime,
   this.deliveryTime,
   this.deliveryZone,
  this.clientFirstName,
    this.clientLastName,
  this.restoName,
 this.restoImagePath,
 this.nbrProduct,
  this.status,
  this.latitude,
  this.longitude,
 });

   factory OrderListData.fromJson(Map<String, dynamic> json) {
  return OrderListData(
  orderID: json['Orders'][0]['orderID'],
  orderDate: json['Orders'][0]['orderDate'],
  deliveryWishedTime: json['Orders'][0]['deliveryWishedTime'],
  deliveryTime: json['Orders'][0]['deliveryTime'],
  deliveryZone: json['Orders'][0]['deliveryZone'],
  clientFirstName: json['Orders'][0]['clientFirstName'],
  clientLastName: json['Orders'][0]['clientLastName'],
  restoName: json['Orders'][0]['restoName'],
  restoImagePath: json['Orders'][0]['restoImagePath'],
  nbrProduct: json['Orders'][0]['nbrProduct'],
  status: json['Orders'][0]['status'],
  latitude: json['Orders'][0]['latitude'],
  longitude: json['Orders'][0]['longitude'],
  );
 }
 }

您應該在第二個屏幕中有一個構造函數:

class SecondScreen extends StatefulWidget {

  final int id;

  const SecondScreen({Key key, this.id}) : super(key: key);@override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}

並像這樣傳遞它:

    Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context)=>SecondScreen(id: 1,)), (route) => false)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM