英文:
How to return a DataRow in a StatefulWidget in flutter?
问题
以下是翻译好的部分:
"Hi i'm making an app multiplatform, and i want display the data in a table in desktops, and in cards in mobile. I already have the view of the cards created with all the methods but when i try to returns a DataRow instead it gives me an error because DataRow is not a Widget. I want to make it in the same class so it can maintain the state. Is there any way or workaround to achieve this?
I expect something like this:
class MainView extends StatefulWidget {
const MainView({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _MainViewState();
}
class _MainViewState extends State<MainView> {
@override
Widget build(BuildContext context) {
return isMobile ? Card( /* .... */ ) : DataRow( /* .... */ );
}
}
"
英文:
Hi i'm making an app multiplatform, and i want display the data in a table in desktops, and in cards in mobile. I already have the view of the cards created with all the methods but when i try to returns a DataRow instead it gives me an error because DataRow is not a Widget. I want to make it in the same class so it can maintain the state. Is there any way or workaround to achieve this?
I expect something like this:
class MainView extends StatefulWidget {
const MainView({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _MainViewState();
}
class _MainViewState extends State<MainView> {
@override
Widget build(BuildContext context) {
return isMobile ? Card( /* .... */ ) : DataRow( /* .... */ );
}
}
答案1
得分: 1
我假设您不想在您的应用程序中显示单个Card
或DataRow
,而是要显示一系列卡片或包含多个数据行的表格。因此,创建两个方法,将您要显示的数据转换为Card
或DataRow
的列表,然后根据平台调用所需的方法,并将结果列表包装在ListView
或DataTable
中。ListView
和DataTable
都是小部件,因此您的StatefulWidget
的build
函数将不再产生任何错误。
类似这样的代码:
List<Card> createCardList(data) {...};
List<DataRow> createDataRowList(data) {...};
@override
Widget build(BuildContext context) {
return isMobile
? ListView(children: createCardList(dataFromBackEnd))
: DataTable(
columns: const <DataColumn>[...],
rows: createDataRowList(dataFromBackEnd),
);
}
英文:
I am assuming you don't want to display a single Card
or DataRow
in your app but rather a list of cards or a table consisting of several data rows. So create two methods that will turn the data you want to display into a list of Card
s or DataRow
s, then call the method that you need based on the platform, and wrap your resulting list in a ListView
or DataTable
. Both ListView
and DataTable
are widgets, so the build
function of your StatefulWidget
will no longer give you any errors.
Something like this:
List<Card> createCardList (data){...};
List<DataRow> createDataRowList(data){...};
@override
Widget build(BuildContext context) {
return isMobile
? ListView(children: createCardList(dataFromBackEnd))
: DataTable(
columns: const <DataColumn>[...],
rows: createDataRowList(dataFromBackEnd),
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论