Home > Enterprise >  how to refresh page after send POST API in flutter
how to refresh page after send POST API in flutter

Time:03-05

I have a POST API that when I send a request, I give the GET API request on the same screen to show the json data. When I send information, after sending the information, the Get data is not displayed and must be logged out to display GET API data.

How can I refresh the page after sending the POST API data, so that the information is displayed after sending

POST API:

  void ladderAsli() async {
    if (_avgWeeklySales.text.isNotEmpty) {
      print(token);
      var response = await http.post(
          Uri.parse("localhost/backend/api/v1/pellekan/main/add/"),
          body: ({
            "avgWeeklySales": _avgWeeklySales.text,
          }),
          headers: {
            'Authorization': 'Bearer $token',
          });
      var body = jsonDecode(response.body);

      if (response.statusCode == 200) {
        SharedPreferences pref = await SharedPreferences.getInstance();
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${body['success']}')));
      } else {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${body['error']}')));
      }
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('error')));
    }
  }

and GET API:

  Future getDataLadder() async {
    print('bye');
    String token = await getToken();
    var response = await http.get(
        Uri.parse('localhost/backend/api/v1/pellekan/main/active'),
        headers: {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        });
    print('Token : ${token}');
    print('Response Body : ${response.body}');

    if (response.statusCode == 400) {
      var chieIN = jsonDecode(response.body);
      print("be moshkel khordim hich dataei nist");
    }
    if (response.statusCode == 200) {
      var chieIN = jsonDecode(response.body);
      // print('Hosssssein '  
      //     chieIN['pellekanInfo']['pellekanPublishStatus'].toString());
      val = chieIN['pellekanInfo']['pellekanPublishStatus'].toString();
      print('BODOBA : ${val}');
      setState(() {
        val = '0';
      });
      //setState(() {
      // stringResponse = jsonDecode(response.body)['pellekan'];
      // val!.add(chieIN['pellekanInfo']['pellekanPublishStatus'].toString());
      stringResponse = [];
      stringResponse.addAll(List<NardebanData>.from(json
          .decode(response.body)['pellekan']
          .map((x) => NardebanData.fromJson(x))));
      print('String Response : ${stringResponse}');
      // nardeban_data = (stringResponse as List<NardebanData>).map((d) => NardebanData.fromJson(d)).toList();
      //});
    } else {
      print("error");
    }
  }

in the initState call getDataLadder()

Refreshpage

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:project/pattern_formatter.dart';
import 'package:project/screens/result-ladder.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

List<NardebanData> nardeban_data = [];
List<NardebanData> stringResponse = [];

class Ladder extends StatefulWidget {
  const Ladder({Key? key}) : super(key: key);

  @override
  _LadderState createState() => _LadderState();
}

Future<String> getToken() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('login')!;
}

class _LadderState extends State<Ladder> {
  bool value = true;
  String? val = "";

  String token = "";
  @override
  void initState() {
    super.initState();
    getDataLadder();
    getInfo();
  }

  void getInfo() async {
    SharedPreferences pref = await SharedPreferences.getInstance();

    setState(() {
      token = pref.getString("login")!;
    });
  }

  TextEditingController _avgWeeklySales = TextEditingController();
  TextEditingController _doubleSellingPricePercent = TextEditingController();
  TextEditingController _tripleSellingPricePercent = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: Directionality(
            textDirection: TextDirection.rtl, child: gochgochApp()));
  }

  Future getDataLadder() async {
    print('bye');
    String token = await getToken();
    var response = await http.get(
        Uri.parse('localhost/backend/api/v1/pellekan/main/active'),
        headers: {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        });
    print('Token : ${token}');
    print('Response Body : ${response.body}');

    if (response.statusCode == 400) {
      var chieIN = jsonDecode(response.body);
      print("be moshkel khordim hich dataei nist");
    }
    if (response.statusCode == 200) {
      var chieIN = jsonDecode(response.body);
      // print('Hosssssein '  
      //     chieIN['pellekanInfo']['pellekanPublishStatus'].toString());
      val = chieIN['pellekanInfo']['pellekanPublishStatus'].toString();
      print('BODOBA : ${val}');
      setState(() {
        val = '0';
      });
      //setState(() {
      // stringResponse = jsonDecode(response.body)['pellekan'];
      // val!.add(chieIN['pellekanInfo']['pellekanPublishStatus'].toString());
      stringResponse = [];
      stringResponse.addAll(List<NardebanData>.from(json
          .decode(response.body)['pellekan']
          .map((x) => NardebanData.fromJson(x))));
      print('String Response : ${stringResponse}');
      // nardeban_data = (stringResponse as List<NardebanData>).map((d) => NardebanData.fromJson(d)).toList();
      //});
    } else {
      print("hooooooooooooooooooooooooo");
    }
  }

  // Future asyncokeyeData() async {
  //   SharedPreferences pref = await SharedPreferences.getInstance();
  //   val = pref.getString('okeyeData');
  // }

  Widget gochgochApp() {
    print('Valiable : ${val}');
    if (val == '0') {
      print(val);
      // return Container(
      //   height: 200.0,
      //   child: Center(child: Text('شما در انتظار تایید نیست')),
      // );
      // return alertInForProcessLadder();

      return getBody();

      // return getBody();
    }
    // if (val == '2' || val == null) {
    //   return getForm();
    // }
    else {
      return getForm();
    }
  }

  Widget alertInForProcessLadder() {
    return (SafeArea(
      child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 30, vertical: 24),
          child: SingleChildScrollView(
            child: Container(
              child: Center(
                  child: Text(
                      'شما یک پلکان اصلی در انتظار تایید ادمین دارید و نمی توانید پلکان دیگری ایجاد کنید')),
              height: 200.0,
            ),
          )),
    ));
  }

  Widget getForm() {
    return (SafeArea(
      child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 30, vertical: 24),
          child: SingleChildScrollView(
            child: Column(
              children: [
                SizedBox(
                  height: 9,
                ),
                Text(
                  "فرم نردبان اصلی",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 18,
                    color: Colors.blue,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Container(
                  padding: EdgeInsets.all(28),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Column(
                    children: [
                      Text(
                        'مبلغ را به تومان وارد کنید',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.black54,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      TextField(
                        controller: _avgWeeklySales,
                        textAlign: TextAlign.center,
                        cursorColor: Colors.blue,
                        keyboardType: TextInputType.number,
                        inputFormatters: [ThousandsFormatter()],
                        decoration: InputDecoration(
                          hintStyle:
                              TextStyle(color: Colors.black26, fontSize: 13),
                          hintText: 'مثال : 1,000,000',
                          border: OutlineInputBorder(),
                          hintTextDirection: TextDirection.rtl,
                          contentPadding: EdgeInsets.all(8),
                        ),
                      ),
                      SizedBox(
                        height: 22,
                      ),
                      Text(
                        'درصد تخفیف برای 20 عدد',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.black54,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      TextField(
                        controller: _doubleSellingPricePercent,
                        textAlign: TextAlign.center,
                        cursorColor: Colors.blue,
                        keyboardType: TextInputType.number,
                        inputFormatters: [ThousandsFormatter()],
                        decoration: InputDecoration(
                          hintStyle:
                              TextStyle(color: Colors.black26, fontSize: 13),
                          hintText: 'مثال : 20',
                          border: OutlineInputBorder(),
                          hintTextDirection: TextDirection.rtl,
                          contentPadding: EdgeInsets.all(8),
                        ),
                      ),
                      SizedBox(
                        height: 22,
                      ),
                      Text(
                        'درصد تخفیف برای 30 عدد',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.black54,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      TextField(
                        controller: _tripleSellingPricePercent,
                        textAlign: TextAlign.center,
                        cursorColor: Colors.blue,
                        keyboardType: TextInputType.number,
                        inputFormatters: [ThousandsFormatter()],
                        decoration: InputDecoration(
                          hintStyle:
                              TextStyle(color: Colors.black26, fontSize: 13),
                          hintText: 'مثال : 30',
                          border: OutlineInputBorder(),
                          hintTextDirection: TextDirection.rtl,
                          contentPadding: EdgeInsets.all(8),
                        ),
                      ),
                      SizedBox(
                        height: 25,
                      ),
                      SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          onPressed: () {
                            ladderAsli();
                          },
                          style: ButtonStyle(
                            shape: MaterialStateProperty.all<
                                RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(15.0),
                              ),
                            ),
                            foregroundColor:
                                MaterialStateProperty.all<Color>(Colors.white),
                            backgroundColor:
                                MaterialStateProperty.all<Color>(Colors.blue),
                          ),
                          child: Padding(
                            child: Text(
                              'تایید',
                              style: TextStyle(
                                  fontWeight: FontWeight.bold, fontSize: 21),
                            ),
                            padding: EdgeInsets.all(15.0),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          )),
    ));
  }

  Widget getBody() {
    var size = MediaQuery.of(context).size;
    return Container(
      width: size.width,
      height: size.height,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10)),
          color: Colors.white),
      child: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(
              height: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Flexible(
                  child: Container(
                    height: 1,
                    decoration:
                        BoxDecoration(color: Colors.grey.withOpacity(0.2)),
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                buildHeader(
                  text: 'جهت فعال سازی پله 30 عددی فیلد زیر را فعال کنید',
                  child: buildSwitch(),
                ),
                SizedBox(
                  width: 10,
                ),
                Flexible(
                  child: Container(
                    height: 1,
                    decoration:
                        BoxDecoration(color: Colors.grey.withOpacity(0.2)),
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 15,
            ),
            Column(
                children: List.generate(stringResponse.length, (index) {
              NardebanData dataItem = stringResponse[index];
              return Column(
                children: [
                  Padding(
                      padding: const EdgeInsets.only(right: 5, left: 5),
                      child: Container(
                        decoration: new BoxDecoration(
                          image: new DecorationImage(
                            image: new AssetImage("assets/images/bg.png"),
                            fit: BoxFit.fill,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              height: 90,
                              // width: (size.width - 20) * 0.68,
                              child: Row(
                                children: [
                                  SizedBox(width: 20), // give it width
                                  Container(
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.blue,
                                          border:
                                              Border.all(color: Colors.blue),
                                          borderRadius:
                                              BorderRadius.circular(40.0)),
                                      child: Padding(
                                          padding: EdgeInsets.all(10.0),
                                          child: Text(dataItem.name!,
                                              textAlign: TextAlign.center,
                                              style: TextStyle(
                                                  fontSize: 12.5,
                                                  fontWeight: FontWeight.bold,
                                                  color: Colors.white)))),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Container(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          dataItem.form ?? ''   '',
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.black54,
                                              fontWeight: FontWeight.w400),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          ' تا '   dataItem.to!,
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.black54,
                                              fontWeight: FontWeight.w400),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ),
                            Container(
                              width: (size.width - 120) * 0.32,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        border: Border.all(color: Colors.blue)),
                                    child: Padding(
                                      padding: const EdgeInsets.only(
                                          right: 10,
                                          bottom: 4,
                                          left: 10,
                                          top: 4),
                                      child: Row(
                                        children: [
                                          SizedBox(
                                            width: 25,
                                            height: 25,
                                            child: TextField(
                                              textAlign: TextAlign.center,
                                              keyboardType:
                                                  TextInputType.number,
                                              decoration: InputDecoration(
                                                hintText: dataItem.percent!,
                                                border: InputBorder.none,
                                                contentPadding: EdgeInsets.only(
                                                  bottom: 8,
                                                  top: 3,
                                                ),
                                              ),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                  // Icon(
                                  //   Icons.notifications,
                                  //   size: 22,
                                  //   color: Colors.blue.withOpacity(0.7),
                                  // )
                                ],
                              ),
                            )
                          ],
                        ),
                      )),
                ],
              );
            })),
          ],
        ),
      ),
    );
  }

  Widget buildHeader({
    required Widget child,
    required String text,
  }) =>
      Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            text,
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 3),
          child,
        ],
      );

  Widget buildSwitch() => Transform.scale(
        scale: 2,
        child: Switch.adaptive(
          activeColor: Colors.blueAccent,
          activeTrackColor: Colors.blue.withOpacity(0.4),
          // inactiveThumbColor: Colors.orange,
          // inactiveTrackColor: Colors.black87,
          splashRadius: 50,
          value: value,
          onChanged: (value) => setState(() => this.value = value),
        ),
      );

  void ladderAsli() async {
    if (_avgWeeklySales.text.isNotEmpty) {
      print(token);
      var response = await http.post(
          Uri.parse("localhost/backend/api/v1/pellekan/main/add/"),
          body: ({
            "avgWeeklySales": _avgWeeklySales.text,
            "doubleSellingPricePercent": _doubleSellingPricePercent.text,
            "tripleSellingPricePercent": _tripleSellingPricePercent.text,
          }),
          headers: {
            'Authorization': 'Bearer $token',
          });
      var body = jsonDecode(response.body);

      if (response.statusCode == 200) {
        SharedPreferences pref = await SharedPreferences.getInstance();
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${body['success']}')));
      } else {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${body['error']}')));
      }
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('مبلغ کل را وارد کنید')));
    }
  }
}

this is json sample:

{
    "pellekan": [
        {
            "name": "پله 1",
            "form": null,
            "to": "9999",
            "percent": 1
        },
        {
            "name": "پله 2",
            "form": "9999",
            "to": 10.74,
            "percent": 2.89
        },
        {
    ]
}

CodePudding user response:

enter image description here

Listview.builder widget used to propagate the change in ui

ListView.builder(
                itemCount: datajson!.length,
                itemBuilder: (context, index) {
                  return Text(datajson![index].toString(),
                      style: TextStyle(fontSize: 10));
                })

Here i use sample post and getmethod with future delay like mimic the api wait and supply the data.

void MygetData() {
    Future.delayed(Duration(seconds: 3), () {
      setState(() {
        isloading = false;

        datajson;
      });
    });
  }
  void posts() {
    Future.delayed(Duration(seconds: 3), () {
      // other post request

      datajson?.add({"name": "2"});
      MygetData();
    });
  }

SampleCode dartpad live

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

int myvalue = 0;
List<Map<String, dynamic>>? datajson = [];

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  bool isloading = false;

  @override
  void initState() {
    isloading = true;

    Future.delayed(Duration(seconds: 3), () {
      setState(() {
        datajson?.add({"name": "1"});
        isloading = false;
      });
    });
  }

  void MygetData() {
    Future.delayed(Duration(seconds: 3), () {
      setState(() {
        isloading = false;

        datajson;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
// shrinkWrap: true,
        children: [
          Container(
            height: 45,
            child: ElevatedButton(
                onPressed: () {
                  setState(() {
                    isloading = true;
                  });

                  posts();
                },
                child: Text(
                  "Post",
                  style: TextStyle(fontSize: 10),
                )),
          ),
          Expanded(
            child: ListView.builder(
                itemCount: datajson!.length,
                itemBuilder: (context, index) {
                  return Text(datajson![index].toString(),
                      style: TextStyle(fontSize: 10));
                }),
          ),
          isloading
              ? Container(
                  height: 50,
                  width: 50,
                  child: CircularProgressIndicator(),
                )
              : Text("")
        ],
      ),
    );
  }

  void posts() {
    Future.delayed(Duration(seconds: 3), () {
      // other post request

      datajson?.add({"name": "2"});
      MygetData();
    });
  }
}

CodePudding user response:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:project/pattern_formatter.dart';
import 'package:project/screens/result-ladder.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

List<NardebanData> nardeban_data = [];
List<NardebanData> stringResponse = [];

class Ladder extends StatefulWidget {
  const Ladder({Key? key}) : super(key: key);

  @override
  _LadderState createState() => _LadderState();
}

Future<String> getToken() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('login')!;
}

class _LadderState extends State<Ladder> {
  bool value = true;
  String? val = "";

  String token = "";
  @override
  void initState() {
    super.initState();
    getDataLadder();
    getInfo();
  }

  void getInfo() async {
    SharedPreferences pref = await SharedPreferences.getInstance();

    setState(() {
      token = pref.getString("login")!;
    });
  }

  TextEditingController _avgWeeklySales = TextEditingController();
  TextEditingController _doubleSellingPricePercent = TextEditingController();
  TextEditingController _tripleSellingPricePercent = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: Directionality(
            textDirection: TextDirection.rtl, child: gochgochApp()));
  }

  Future getDataLadder() async {
    print('bye');
    String token = await getToken();
    var response = await http.get(
        Uri.parse('localhost/backend/api/v1/pellekan/main/active'),
        headers: {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        });
    print('Token : ${token}');
    print('Response Body : ${response.body}');

    if (response.statusCode == 400) {
      var chieIN = jsonDecode(response.body);
      print("be moshkel khordim hich dataei nist");
    }
    if (response.statusCode == 200) {
      var chieIN = jsonDecode(response.body);
      // print('Hosssssein '  
      //     chieIN['pellekanInfo']['pellekanPublishStatus'].toString());
      val = chieIN['pellekanInfo']['pellekanPublishStatus'].toString();
      print('BODOBA : ${val}');
      setState(() {
        val = '0';
      });
      //setState(() {
      // stringResponse = jsonDecode(response.body)['pellekan'];
      // val!.add(chieIN['pellekanInfo']['pellekanPublishStatus'].toString());
      stringResponse = [];
      stringResponse.addAll(List<NardebanData>.from(json
          .decode(response.body)['pellekan']
          .map((x) => NardebanData.fromJson(x))));
      print('String Response : ${stringResponse}');
      // nardeban_data = (stringResponse as List<NardebanData>).map((d) => NardebanData.fromJson(d)).toList();
      //});
    } else {
      print("hooooooooooooooooooooooooo");
    }
  }

  // Future asyncokeyeData() async {
  //   SharedPreferences pref = await SharedPreferences.getInstance();
  //   val = pref.getString('okeyeData');
  // }

  Widget gochgochApp() {
    print('Valiable : ${val}');
    if (val == '0') {
      print(val);
      // return Container(
      //   height: 200.0,
      //   child: Center(child: Text('شما در انتظار تایید نیست')),
      // );
      // return alertInForProcessLadder();

      return getBody();

      // return getBody();
    }
    // if (val == '2' || val == null) {
    //   return getForm();
    // }
    else {
      return getForm();
    }
  }

  Widget alertInForProcessLadder() {
    return (SafeArea(
      child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 30, vertical: 24),
          child: SingleChildScrollView(
            child: Container(
              child: Center(
                  child: Text(
                      'شما یک پلکان اصلی در انتظار تایید ادمین دارید و نمی توانید پلکان دیگری ایجاد کنید')),
              height: 200.0,
            ),
          )),
    ));
  }

  Widget getForm() {
    return (SafeArea(
      child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 30, vertical: 24),
          child: SingleChildScrollView(
            child: Column(
              children: [
                SizedBox(
                  height: 9,
                ),
                Text(
                  "فرم نردبان اصلی",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 18,
                    color: Colors.blue,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Container(
                  padding: EdgeInsets.all(28),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Column(
                    children: [
                      Text(
                        'مبلغ را به تومان وارد کنید',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.black54,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      TextField(
                        controller: _avgWeeklySales,
                        textAlign: TextAlign.center,
                        cursorColor: Colors.blue,
                        keyboardType: TextInputType.number,
                        inputFormatters: [ThousandsFormatter()],
                        decoration: InputDecoration(
                          hintStyle:
                              TextStyle(color: Colors.black26, fontSize: 13),
                          hintText: 'مثال : 1,000,000',
                          border: OutlineInputBorder(),
                          hintTextDirection: TextDirection.rtl,
                          contentPadding: EdgeInsets.all(8),
                        ),
                      ),
                      SizedBox(
                        height: 22,
                      ),
                      Text(
                        'درصد تخفیف برای 20 عدد',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.black54,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      TextField(
                        controller: _doubleSellingPricePercent,
                        textAlign: TextAlign.center,
                        cursorColor: Colors.blue,
                        keyboardType: TextInputType.number,
                        inputFormatters: [ThousandsFormatter()],
                        decoration: InputDecoration(
                          hintStyle:
                              TextStyle(color: Colors.black26, fontSize: 13),
                          hintText: 'مثال : 20',
                          border: OutlineInputBorder(),
                          hintTextDirection: TextDirection.rtl,
                          contentPadding: EdgeInsets.all(8),
                        ),
                      ),
                      SizedBox(
                        height: 22,
                      ),
                      Text(
                        'درصد تخفیف برای 30 عدد',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.black54,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      TextField(
                        controller: _tripleSellingPricePercent,
                        textAlign: TextAlign.center,
                        cursorColor: Colors.blue,
                        keyboardType: TextInputType.number,
                        inputFormatters: [ThousandsFormatter()],
                        decoration: InputDecoration(
                          hintStyle:
                              TextStyle(color: Colors.black26, fontSize: 13),
                          hintText: 'مثال : 30',
                          border: OutlineInputBorder(),
                          hintTextDirection: TextDirection.rtl,
                          contentPadding: EdgeInsets.all(8),
                        ),
                      ),
                      SizedBox(
                        height: 25,
                      ),
                      SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          onPressed: () {
                            ladderAsli();
                          },
                          style: ButtonStyle(
                            shape: MaterialStateProperty.all<
                                RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(15.0),
                              ),
                            ),
                            foregroundColor:
                                MaterialStateProperty.all<Color>(Colors.white),
                            backgroundColor:
                                MaterialStateProperty.all<Color>(Colors.blue),
                          ),
                          child: Padding(
                            child: Text(
                              'تایید',
                              style: TextStyle(
                                  fontWeight: FontWeight.bold, fontSize: 21),
                            ),
                            padding: EdgeInsets.all(15.0),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          )),
    ));
  }

  Widget getBody() {
    var size = MediaQuery.of(context).size;
    return Container(
      width: size.width,
      height: size.height,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10)),
          color: Colors.white),
      child: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(
              height: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Flexible(
                  child: Container(
                    height: 1,
                    decoration:
                        BoxDecoration(color: Colors.grey.withOpacity(0.2)),
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                buildHeader(
                  text: 'جهت فعال سازی پله 30 عددی فیلد زیر را فعال کنید',
                  child: buildSwitch(),
                ),
                SizedBox(
                  width: 10,
                ),
                Flexible(
                  child: Container(
                    height: 1,
                    decoration:
                        BoxDecoration(color: Colors.grey.withOpacity(0.2)),
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 15,
            ),
            Column(
                children: List.generate(stringResponse.length, (index) {
              NardebanData dataItem = stringResponse[index];
              return Column(
                children: [
                  Padding(
                      padding: const EdgeInsets.only(right: 5, left: 5),
                      child: Container(
                        decoration: new BoxDecoration(
                          image: new DecorationImage(
                            image: new AssetImage("assets/images/bg.png"),
                            fit: BoxFit.fill,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              height: 90,
                              // width: (size.width - 20) * 0.68,
                              child: Row(
                                children: [
                                  SizedBox(width: 20), // give it width
                                  Container(
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.blue,
                                          border:
                                              Border.all(color: Colors.blue),
                                          borderRadius:
                                              BorderRadius.circular(40.0)),
                                      child: Padding(
                                          padding: EdgeInsets.all(10.0),
                                          child: Text(dataItem.name!,
                                              textAlign: TextAlign.center,
                                              style: TextStyle(
                                                  fontSize: 12.5,
                                                  fontWeight: FontWeight.bold,
                                                  color: Colors.white)))),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Container(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          dataItem.form ?? ''   '',
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.black54,
                                              fontWeight: FontWeight.w400),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          ' تا '   dataItem.to!,
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.black54,
                                              fontWeight: FontWeight.w400),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ),
                            Container(
                              width: (size.width - 120) * 0.32,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        border: Border.all(color: Colors.blue)),
                                    child: Padding(
                                      padding: const EdgeInsets.only(
                                          right: 10,
                                          bottom: 4,
                                          left: 10,
                                          top: 4),
                                      child: Row(
                                        children: [
                                          SizedBox(
                                            width: 25,
                                            height: 25,
                                            child: TextField(
                                              textAlign: TextAlign.center,
                                              keyboardType:
                                                  TextInputType.number,
                                              decoration: InputDecoration(
                                                hintText: dataItem.percent!,
                                                border: InputBorder.none,
                                                contentPadding: EdgeInsets.only(
                                                  bottom: 8,
                                                  top: 3,
                                                ),
                                              ),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                  // Icon(
                                  //   Icons.notifications,
                                  //   size: 22,
                                  //   color: Colors.blue.withOpacity(0.7),
                                  // )
                                ],
                              ),
                            )
                          ],
                        ),
                      )),
                ],
              );
            })),
          ],
        ),
      ),
    );
  }

  Widget buildHeader({
    required Widget child,
    required String text,
  }) =>
      Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            text,
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 3),
          child,
        ],
      );

  Widget buildSwitch() => Transform.scale(
        scale: 2,
        child: Switch.adaptive(
          activeColor: Colors.blueAccent,
          activeTrackColor: Colors.blue.withOpacity(0.4),
          // inactiveThumbColor: Colors.orange,
          // inactiveTrackColor: Colors.black87,
          splashRadius: 50,
          value: value,
          onChanged: (value) => setState(() => this.value = value),
        ),
      );

  void ladderAsli() async {
    if (_avgWeeklySales.text.isNotEmpty) {
      print(token);
      var response = await http.post(
          Uri.parse("localhost/backend/api/v1/pellekan/main/add/"),
          body: ({
            "avgWeeklySales": _avgWeeklySales.text,
            "doubleSellingPricePercent": _doubleSellingPricePercent.text,
            "tripleSellingPricePercent": _tripleSellingPricePercent.text,
          }),
          headers: {
            'Authorization': 'Bearer $token',
          });
      var body = jsonDecode(response.body);

      if (response.statusCode == 200) {
        SharedPreferences pref = await SharedPreferences.getInstance();
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${body['success']}')));
      } else {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${body['error']}')));
      }
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('مبلغ کل را وارد کنید')));
    }
  }
}
  • Related