flutter中切换按钮获取API方法

ogsagwnx  于 2023-01-31  发布在  Flutter
关注(0)|答案(3)|浏览(161)

我创建了一个切换按钮,我把代码如下:

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),
          splashRadius: 50,
          value: value,
          onChanged: (value) => setState(() => this.value = value),
        ),
      );

变量value为:bool value = true;
这工作正常,但我希望这个API /api/v1/main/enable/{userId}在切换打开时运行
并且这个API /api/v1/main/disable/{userId}在关闭切换时运行,我该怎么做?
这两个API是PUT,我已经为GET api编写了代码,它工作正常,但我不知道如何使用这两个PUT api的切换
我编写了如下get代码,它运行良好

print('bye');
    String token = await getToken();
    var response = await http.get(
        Uri.parse('/api/v1/main/active/get'),
        headers: {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        });

    if (response.statusCode == 200) {
      print('ok');
    } else {
      print("no");
    }
  }
flmtquvp

flmtquvp1#

您必须调用API方法并在成功时更改值:

Widget buildSwitch() => Transform.scale(
    scale: 2,
    child: Switch.adaptive(
      activeColor: Colors.blueAccent,
      activeTrackColor: Colors.blue.withOpacity(0.4),
      splashRadius: 50,
      value: value,
      onChanged: (value) async {
        await apiCallMethod().then((success) {
          if (success) {
            setState(() => this.value = value);
          }
        });
      }
    ),
  );
bybem2ql

bybem2ql2#

import 'dart:convert';

import 'package:http/http.dart' as http;
class ApiHelper{

  static String baseUrl = "https://randomuser.me/api/?results=20";

  static Future<List<dynamic>> getUserList(String endPoint) async {
    var response = await http.get(Uri.parse(baseUrl+endPoint));
    return jsonDecode(response.body)['results'];

  }

}
lc8prwob

lc8prwob3#

您可以使用我的包api_toggle来帮助避免在重复单击时多次调用API

相关问题