英文:
I just wanna access my List ? How do I access it and print the data in it
问题
I tried `initstate` but it won't work and I don't know how to access the list I made. I just want to add all the data send to this file in `cartId` and store it in `cartid`, then I want to print it.
```dart
import 'package:flutter/material.dart';
class Cart extends StatefulWidget {
final int cartId;
const Cart(this.cartId, {Key? key}) : super(key: key);
@override
State<Cart> createState() => _CartState();
}
class _CartState extends State<Cart> {
List<int>? cartid;
@override
void initState() {
// TODO: implement initState
super.initState();
cartid!.add(widget.cartId.toInt());
}
@override
Widget build(BuildContext context) {
return Scaffold (
appBar: AppBar(
title: Text('Cart'),
),
body: Text(cartid != null ? '${cartid!.length}' : "Empty"),
);
}
}
<details>
<summary>英文:</summary>
I tried `initstate` but it won't work and I don't know how to access the list I made. I just want to add all the data send to this file in `cartId` and store it in `cartid` , then I want to print it.
import 'package:flutter/material.dart';
class Cart extends StatefulWidget {
final int cartId ;
const Cart(this.cartId,{Key? key}) : super(key: key);
@override
State<Cart> createState() => _CartState();
}
class _CartState extends State<Cart> {
List<int>? cartid;
@override
void initState() {
// TODO: implement initState
super.initState();
cartid!.add(widget.cartId.toInt());
}
@override
Widget build(BuildContext context) {
return Scaffold (
appBar: AppBar(
title: Text('Cart'),
),
body: Text(cartid != null ? '${cartid!.length}' : "Empty"),
);
}
}
</details>
# 答案1
**得分**: 1
```dart
您正在尝试访问您未在任何地方创建的列表。尝试这样做:
```dart
class Cart extends StatefulWidget {
final int cartId;
const Cart(this.cartId, {super.key});
@override
State<Cart> createState() => _CartState();
}
class _CartState extends State<Cart> {
List<int>? cartid;
@override
void initState() {
// TODO: implement initState
super.initState();
cartid = [widget.cartId];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Cart'),
),
body: Text(cartid != null ? '${cartid!.length}' : "Empty"),
);
}
}
<details>
<summary>英文:</summary>
You're trying to access the list that you didn't create anywhere. Try to do this:
```dart
class Cart extends StatefulWidget {
final int cartId;
const Cart(this.cartId,{super.key});
@override
State<Cart> createState() => _CartState();
}
class _CartState extends State<Cart> {
List<int>? cartid;
@override
void initState() {
// TODO: implement initState
super.initState();
cartid = [widget.cartId];
}
@override
Widget build(BuildContext context) {
return Scaffold (
appBar: AppBar(
title: const Text('Cart'),
),
body: Text(cartid != null ? '${cartid!.length}' : "Empty"),
);
}
}
In the example above, we're instantiating the list in the [widget.cartId]
. There are many ways to do that, tho.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论