Flutter API Fetch and Sending Data from One screen to another screen

Issue

When I am logged in through the API I am getting the value User_id which I am able to print on console, but I want to use it on another screen.
So how can I send the data to another screen?
// First Screen

Future postMethod() async {
var api = Uri.parse("https://demo.likemyfiles.com/DS/api/auth/otp");
Map mapeddate = {
  'phone': _phone.text,
  'otp': _otp.text,
};
final response = await http.post(api, body: mapeddate);
print(response.body);
var res = json.decode(response.body);
print(res['user_id']); 
Navigator.pushNamed(context, StartActivity.id);   //here i want to send the User_Id
}

//Second Screen (Start Activity) in this screen there is a function FetchData where i want to use the data

Future fetchdata() async {
var url = await http.get(Uri.parse(
    "http://demo.likemyfiles.com/DS/api/api_supervisor/supervisor/3")); //Instead of 3 i want 
  to use the User_Id variable
 }

Solution

You should try to declare constructor the first page accept the id and push this id to second page or screen like this below code is first page

Navigator.push(
context,
MaterialPageRoute(
  builder: (context) => ABC.withId(
    id,
  ),
 ),
)

the create constructor inside second page screen

class ABC extends StatefulWidget {
  @override
  _ABCState createState() => _ABCState();

  var id;
  
  ABC.withId(String uid) {
    id = uid;
   
  }
}

accept your id inside widget using widget.id

Answered By – Ravindra S. Patil

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *