【问题标题】:Why i am not able to use setState Under GestureDetector为什么我不能在 GestureDetector 下使用 setState
【发布时间】:2021-08-07 13:38:39
【问题描述】:

为什么我无法在 GestureDetector 下使用 onTap 使用 setState:

使用 setState 后,我收到如下错误:未定义函数“setState”。 尝试导入定义 'setState' 的库,然后 VS Code 编辑器告诉我

错误例如:将名称更正为现有函数的名称,或定义名为“setState”的函数.dart(undefined_function)。

我尝试解决不同的方法请告诉我我的问题在哪里 谢谢

一些 Flutter 导入链接 :::::::::::

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

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

class _ParsingMapState extends State<ParsingMap> {
  Future<ApiList>? data;

  @override
  void initState() {
    super.initState();
    Network network = Network("https://fakestoreapi.com/products");
    data = network.loadPosts();
    // print(data);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: Icon(Icons.arrow_left, color: Colors.black),
        actions: [
          Icon(Icons.search, color: Colors.black),
          SizedBox(width: 10),
          Icon(Icons.home_filled, color: Colors.black),
          SizedBox(width: 8)
        ],
      ),
      body: Center(
        child: Container(
          child: FutureBuilder(
            future: data,
            builder: (context, AsyncSnapshot<ApiList> snapshot) {
              List<Api> allPosts;
              if (snapshot.hasData) {
                allPosts = snapshot.data!.apis!;
                return createListView(allPosts, context);
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

class Network {
  final String url;
  Network(this.url);
  Future<ApiList> loadPosts() async {
    final response = await get(Uri.parse(url));
    if (response.statusCode == 200) {
      // print(response.body);
      return ApiList.fromJson(json.decode(response.body));
    } else {
      throw Exception("Faild To get posts");
    }
  }
}

Widget createListView(List<Api> data, BuildContext context) {
  return ListView(
    children: [
      Container(
        height: 300,
        margin: EdgeInsets.symmetric(vertical: 16),
        child: ListView.builder(
          itemCount: data.length,
          scrollDirection: Axis.horizontal,
          physics: BouncingScrollPhysics(),
          padding: EdgeInsets.symmetric(horizontal: 16),
          itemBuilder: (context, index) {
            int selectedIndex = 0;
            return GestureDetector(
              onTap: () {
                setState(() {
                  selectedIndex = index;
                });
              },
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "${data[index].category}",
                      style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: selectedIndex == index
                              ? Colors.black
                              : Colors.black38),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        top: 5,
                      ),
                      height: 2,
                      width: 30,
                      color: selectedIndex == index
                          ? Colors.black
                          : Colors.transparent,
                    )
                  ],
                ),
              ),
            );
          },
        ),
      ),
    ],
  );
}

【问题讨论】:

  • 我认为 setState() 是在其上下文(StatefulWidget)之外调用的。我的意思是它不能在 StatefulWidget 之外使用,因为我可以看到您的 createListView 不在 StatefulWidget 之外。

标签: flutter dart visual-studio-code


【解决方案1】:

将顶级createListView 函数放入_ParsingMapState 类中。

class _ParsingMapState extends State<ParsingMap> {
   // ...

  Widget createListView(...) {}
}

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2022-10-01
    • 2023-03-26
    • 2021-02-17
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多