Json 如何提高我的应用程序在Flatter中的性能
我正在构建一个名为LiveTv的应用程序,它是一个根据不同兴趣推荐视频的应用程序。我编写的代码造成了严重的延迟,并且随着我在这个应用程序中的操作越来越多,它几乎无法运行。我已经在这个链接中包含了相同的视频 我所做的是使调用异步,并且我使用了一个三元运算符,在它下面显示了一个循环进度指示器。但是它似乎只起作用 我已经包括了由底部导航栏控制的代码。它的服务部分不包括在内,因为它的功能只是加载数据或对象,但我将包括一个或两个,以便您理解,我不想让这个问题太长Json 如何提高我的应用程序在Flatter中的性能,json,performance,flutter,dart,Json,Performance,Flutter,Dart,我正在构建一个名为LiveTv的应用程序,它是一个根据不同兴趣推荐视频的应用程序。我编写的代码造成了严重的延迟,并且随着我在这个应用程序中的操作越来越多,它几乎无法运行。我已经在这个链接中包含了相同的视频 我所做的是使调用异步,并且我使用了一个三元运算符,在它下面显示了一个循环进度指示器。但是它似乎只起作用 我已经包括了由底部导航栏控制的代码。它的服务部分不包括在内,因为它的功能只是加载数据或对象,但我将包括一个或两个,以便您理解,我不想让这个问题太长 class LiveTvHomePage
class LiveTvHomePage extends StatefulWidget {
final String title;
LiveTvHomePage({
this.title,
});
@override
_LiveTvHomePageState createState() => _LiveTvHomePageState();
}
class _LiveTvHomePageState extends State<LiveTvHomePage> {
//GlobalKey<ScaffoldState> _drawerKey = GlobalKey<ScaffoldState>();
@override
void initState() {
// TODO: implement initState
super.initState();
handleScroll(); // function which is responsible for updating the isScrollingDown variable whenever the user scrolls down
_services();
setState(() {
_isLoading = false;
});
}
_loadingImage() {
return CircularProgressIndicator();
}
_services() {
Services.loadDataForMovieId().then((movieIdList) {
setState(() {
_homeBannerObjectMovieIdList = movieIdList;
});
});
Services.loadDataForMovieIdofPopularMovieSection().then((movieIdList) {
setState(() {
_popularMoviesMovieId = movieIdList;
});
});
Services.loadDataForPopularTvShowSection().then((homePageSeriesPosterList) {
setState(() {
_seriesData = homePageSeriesPosterList;
});
});
Services.loadDataForMusicSection().then((musicList) {
setState(() {
_musicCategories = musicList;
});
});
Services.loadDataForPlaylistTitle().then((title) {
setState(() {
_musicPlaylistThemeName = title;
});
});
Services.loadDataForPopularNewsChannelsNames().then((nameList) {
setState(() {
_popularNewsChannelNames = nameList;
});
});
Services.loadDataForPopularNewsChannelsProfilePicUrls().then((urllist) {
setState(() {
_popularNewsChannelProfilePicUrl = urllist;
});
});
Services.loadDataForLiveNewsChannelsProfilePicUrls().then((urllist) {
setState(() {
_liveNewsChannelProfilePicUrl = urllist;
});
});
Services.loadDataForLiveNewsChannelsNames().then((nameList) {
setState(() {
_liveNewsChannelNames = nameList;
});
});
Services.loadDataForPicOfLatestNews().then((nameList) {
setState(() {
_latestNewsProfilePics = nameList;
});
});
Services.loadDataForOfLatestNewsTitle().then((nameList) {
setState(() {
_latestNewsNewsTitle = nameList;
});
});
Services.loadDataForOfLatestNewsDescription().then((nameList) {
setState(() {
_latestNewsDescription = nameList;
});
});
}
_buildBody(var boxHeight, List<String> youtubeIdUrls) {
return Column(
children: <Widget>[
Stack(
children: <Widget>[
_buildPageView(boxHeight, youtubeIdUrls),
_buildCircleIndicator(youtubeIdUrls),
],
),
],
);
}
_buildPageView(var boxHeight, List<String> youtubeIdUrls) {
return Container(
color: Colors.black87,
height: boxHeight,
child: PageView.builder(
itemCount: 8,
controller: _pageController,
itemBuilder: (BuildContext context, int index) {
try {
// HomeBanner homeBanner=_homeBannelList[index];
return FadeInImage.assetNetwork(
image:
'https://img.youtube.com/vi/${youtubeIdUrls[index].substring(8)}/0.jpg',
placeholder: 'assets/loading.gif',
fit: BoxFit.fill,
);
} catch (e) {
return CircularProgressIndicator();
}
//before return Image.network('https://img.youtube.com/vi/${videoIdOfUrlList[index]}/0.jpg',fit: BoxFit.fill,);
},
onPageChanged: (int index) {
_currentPageNotifier.value = index;
}),
);
}
_buildCircleIndicator(List<String> youtubeIdUrls) {
return Positioned(
left: 0.0,
right: 0.0,
bottom: 0.0,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: CirclePageIndicator(
itemCount: 8,
currentPageNotifier: _currentPageNotifier,
),
),
);
}
Widget imageDisplayed(String picUrl) {
return Row(
children: <Widget>[
const SizedBox(
width: 10,
),
CircleAvatar(
backgroundImage: NetworkImage(picUrl),
radius: MediaQuery.of(context).size.height * 0.08,
backgroundColor: Colors.black,
),
const SizedBox(
width: 10,
),
],
);
}
Widget HorizontalListViewWitCircularCards(
String title, List<String> urlList, List<String> nameList) {
return Container(
color: Colors.black,
height: MediaQuery.of(context).size.height * 0.32,
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.07,
color: Colors.black,
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
child: Text(
title,
style: TextStyle(fontSize: 16, color: Colors.white),
),
),
),
Container(
height: MediaQuery.of(context).size.height * 0.23,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: _popularNewsChannelNames.length,
itemBuilder: (BuildContext context, int index) => Card(
color: Colors.black,
child: Padding(
padding: const EdgeInsets.symmetric(),
child: Column(
children: <Widget>[
imageDisplayed(urlList[index]),
const SizedBox(
height: 13,
),
Text(
nameList[index],
style: TextStyle(color: Colors.white),
),
],
),
),
),
),
),
],
),
);
}
Widget HorizontalGridViewOfCardsofGradientColor(int count, List<String> lst) {
return Container(
color: Colors.black,
height: MediaQuery.of(context).size.height * 0.125 * count,
child: GridView.count(
scrollDirection: Axis.horizontal,
crossAxisCount: count,
shrinkWrap: true,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
children: List.generate(20, (index) {
return Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
),
borderRadius: BorderRadius.all(Radius.circular(15)),
gradient: LinearGradient(colors: colorsForCardinMusicPage[index]),
),
child: Center(
child: Text(
lst[index],
),
),
);
}),
),
);
}
Widget HorizontalGridViewOfCardsofGradientColorWithtitle(
int count, String title) {
return Column(
);
}
Widget HorizontalListViewOfButtons(List moviesPageButtonNames) {
return Container(
color: Colors.black,
height: MediaQuery.of(context).size.height * 0.13,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: moviesPageButtonNames.length,
itemBuilder: (BuildContext context, int index) => Row(
children: <Widget>[
SizedBox(
width: 7,
),
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.grey)),
color: Colors.grey[800],
textColor: Colors.white,
onPressed: () {},
child: Text(moviesPageButtonNames[index]),
),
SizedBox(
width: 10,
)
],
),
),
);
}
Widget NewsPageOfBottomNavigator() {
ServicesForNewsPage.loadObjectList().then((newsPageObject) {
_newsPage = newsPageObject;
});
for (var obj in _newsPage.liveChannels) {
_newsPageLiveNewsUrls.add(obj.publisherProfilePic);
_newsPageChannelName.add(obj.publisherName);
}
// print("_newsPageLiveNewsUrls");
// print(_newsPageLiveNewsUrls);
// print("_newsPageLiveNewsNames");
// print(_newsPageChannelName);`
for (var obj in _newsPage.news) {
_newsPagePopularNewsChannelUrls.add(obj.publishers.profilePicUrl);
_newsPagePopularNewsChannelNames.add(obj.publishers.fullName);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
HorizontalListViewWithoutViewAllForLiveNewsChannels(
"Watch Live", _newsPageLiveNewsUrls, _newsPageChannelName),
HorizontalListViewWitCircularCards("Popular News Channel",
_newsPagePopularNewsChannelUrls, _newsPagePopularNewsChannelNames),
VerticalListView(_newsPagePopularNewsChannelNames, true),
],
);
}
Widget LifeStylePageOfBottomNavigator() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
HorizontalListViewWitCircularCards(
"Popular Lifestyle channels", [""], [""]),
VerticalListView(["ssss"], false),
],
);
}
Widget SportsPageOfBottomNavigator() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
HorizontalListViewWitCircularCards(
"Popular Sports channels", [""], [""]),
VerticalListView(["ssss"], false),
],
);
}
Widget returnToTopButton() {
return Visibility(
visible: _showButton,
child: FlatButton(
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0, 7, 0, 0),
child: Text(
"^",
style: TextStyle(color: Colors.white, fontSize: 27),
),
),
Text(
" Return to top",
style: TextStyle(color: Colors.white),
),
],
),
onPressed: () {
_scrollController.animateTo(0,
duration: Duration(milliseconds: 500), curve: Curves.easeInOut);
},
color: Colors.red,
),
);
}
void showFloationButton() {
setState(() {
_showButton = true;
});
}
void hideFloationButton() {
setState(() {
_showButton = false;
});
}
void handleScroll() async {
// or something else..
_scrollController.addListener(() {
double currentScroll = _scrollController.position.pixels;
double delta = MediaQuery.of(context).size.height;
// print("Current scroll position is ..........$currentScroll");
// print("delta pixel is ..........$delta");
if (currentScroll >= delta) {
showFloationButton();
} else if (currentScroll <= delta) {
hideFloationButton();
}
});
}
@override
void dispose() {
// TODO: implement dispose
_scrollController.removeListener(() {});
super.dispose();
}
@override
Widget build(BuildContext context) {
List<Widget> wdgs_option = [
HomePageForBottomNavigator(),
MoviesPageForBottomNavigator(),
TvSHowsPageOfBottomNavigator(),
MusicPageofBottomNavigator(),
// NewsPageOfBottomNavigator(), //dummy for now
NewsPageOfBottomNavigator(),
LifeStylePageOfBottomNavigator(),
SportsPageOfBottomNavigator()
];
return _isLoading
? _loadingImage()
: Scaffold(
// key: _drawerKey,
appBar: AppBar(
automaticallyImplyLeading: false,
leading: Icon(
Icons.live_tv,
color: Colors.amber,
),
backgroundColor: Colors.black,
title: Text(
widget.title,
style: TextStyle(fontSize: 17, color: Colors.amber),
),
actions: <Widget>[
IconButton(
tooltip: 'Search',
icon: const Icon(Icons.search),
onPressed: () {},
),
IconButton(
icon: Icon(
MaterialCommunityIcons.xbox_controller_menu,
color: Colors.white,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => DrawerWidget()),
);
},
)
],
),
body: SafeArea(
child: SingleChildScrollView(
controller: _scrollController,
child: wdgs_option.elementAt(_selectedIndex),
),
),
drawer: Drawer(),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.black,
showUnselectedLabels: true,
type: BottomNavigationBarType.shifting,
currentIndex: _selectedIndex,
fixedColor: Colors.amber,
onTap: _onItemTapped,
items: const <BottomNavigationBarItem>[
// Icon(
// FontAwesome.facebook_square,
// color: Colors.amber,
// ),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(
MaterialCommunityIcons.video_vintage,
),
title: Text(
'Movies',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.live_tv),
title: Text(
'Tv shows',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.music_video),
title: Text(
'Music',
),
),
// BottomNavigationBarItem(
// backgroundColor: Colors.black,
// icon: Icon(Icons.dehaze),
// title: Text(
// 'More',
// ),
// ),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.radio),
title: Text(
'News',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(
FontAwesome.heartbeat,
),
title: Text(
'LifeStyle',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(
Ionicons.md_football,
),
title: Text(
'Sports',
),
),
],
),
);
}
}
class LiveTvHomePage扩展StatefulWidget{
最后的字符串标题;
直播电视主页({
这个名字,
});
@凌驾
_LiveTvHomePageState createState()=>\u LiveTvHomePageState();
}
类_LiveTvHomePageState扩展状态{
//GlobalKey _drawerKey=GlobalKey();
@凌驾
void initState(){
//TODO:实现initState
super.initState();
handleScroll();//函数,该函数负责在用户向下滚动时更新isScrollingDown变量
_服务();
设置状态(){
_isLoading=false;
});
}
_加载图像(){
返回循环ProgressIndicator();
}
_服务(){
Services.loadDataForMovieId().then((movieIdList){
设置状态(){
_homeBannerObjectMovieIdList=电影IDList;
});
});
Services.loadDataFormoviedOfPopularMovieSection().then((movieIdList){
设置状态(){
_popularMoviesMovieId=电影列表;
});
});
Services.loadDataForPopularTvShowSection().then((homePageSeriesPosterList){
设置状态(){
_seriesData=主页SeriesPosterList;
});
});
Services.loadDataForMusicSection().then((musicList){
设置状态(){
_musicCategories=musicList;
});
});
Services.loadDataForPlayTitle()。然后((标题){
设置状态(){
_MusicLayListTheMeName=标题;
});
});
Services.LoadDataForPopularNewChannelsNames()。然后((名称列表){
设置状态(){
_PopularNewChannelNames=名称列表;
});
});
Services.loadDataForPopularNewChannelsProfilePicUrls()。然后((URL列表){
设置状态(){
_PopularNewChannelProfilePicUrl=urllist;
});
});
Services.loadDataForLiveNewsChannelsProfilePicUrls()。然后((urllist){
设置状态(){
_liveNewsChannelProfilePicUrl=urllist;
});
});
Services.loadDataForLiveNewsChannelsNames()。然后((名称列表){
设置状态(){
_liveNewsChannelNames=名称列表;
});
});
Services.loadDataForPicOfLatestNews()。然后((名称列表){
设置状态(){
_latestNewsProfilePics=名称列表;
});
});
Services.loadDataForOfLatestNewsTitle()。然后((名称列表){
设置状态(){
_LatestNewsTitle=名称列表;
});
});
Services.loadDataForOfLatestNewsDescription()。然后((名称列表){
设置状态(){
_latestNewsDescription=名称列表;
});
});
}
_buildBody(变量boxHeight,列表youtubeIdUrls){
返回列(
儿童:[
堆叠(
儿童:[
_buildPageView(框高、youtubeIdUrls),
_buildCircleIndicator(youtubeIdUrls),
],
),
],
);
}
_buildPageView(变量boxHeight,列表youtubeIdUrls){
返回容器(
颜色:颜色。黑色87,
高度:箱高,
子项:PageView.builder(
物品计数:8,
控制器:_pageController,
itemBuilder:(构建上下文,int索引){
试一试{
//HomeBanner HomeBanner=_homeBannelList[索引];
返回FadeInImage.assetNetwork(
图片:
'https://img.youtube.com/vi/${youtubeIdUrls[index].子字符串(8)}/0.jpg',
占位符:“assets/loading.gif”,
fit:BoxFit.fill,
);
}捕获(e){
返回循环ProgressIndicator();
}
//返回Image.network之前('https://img.youtube.com/vi/${videoIdOfUrlList[index]}/0.jpg',fit:BoxFit.fill,);
},
onPageChanged:(int索引){
_currentPageNotifier.value=索引;
}),
);
}
_buildCircleIndicator(列出YouTubedURL){
返回定位(
左:0.0,
右:0.0,
底部:0.0,
孩子:填充(
填充:常数边集全部(8.0),
子:CirclePageIndicator(
物品计数:8,
currentPageNotifier:\u currentPageNotifier,
),
),
);
}
显示的小部件图像(字符串picUrl){
返回行(
儿童:[
常量大小框(
宽度:10,
),
圆形(
背景图片:NetworkImage(picUrl),
半径:MediaQuery.of(上下文).size.height*0.08,
背景颜色:Colors.black,
),
常量大小框(
宽度:10,
),
],
);
}
Widget horizontallListViewWithCircularCards(
字符串标题、列表URL列表、列表名称列表){
返回容器(
颜色:颜色,黑色,
高度:MediaQuery.of(context).size.height*0.32,
宽度:MediaQuery.of(context).size.width,
子:列(
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
容器(
高度:MediaQuery.of(上下文).size.height*0.07,
颜色:颜色,黑色,
对齐:alignment.centerLeft,
孩子:填充(
padding:const EdgeInsets.fromLTRB(10,0,0,0),
子:文本(
标题
样式:TextStyle(字体大小:16,颜色:Colors.white),
),
),
),
class ServicesForNewsPage {
static const String url =
"https://livetvapi.apyhi.com/api/v3/home?pageLocation=News&countries=IN&app_version=13&"
"user_id=44edc2c905ae163f&package_id=livetv.movies.freemovies.watchtv.tvshows&os_platform=android";
static Future<NewsPage> loadObjectList() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
// print("response is there for news Page");
final newsPageObjectList = newsPageFromJson(res.body);
return newsPageObjectList;
} else {
print("no response");
return null;
}
}
}
List<Widget> wdgs_option = [
HomePageForBottomNavigator(),
MoviesPageForBottomNavigator(),
TvSHowsPageOfBottomNavigator(),
MusicPageofBottomNavigator(),
// NewsPageOfBottomNavigator(), //dummy for now
NewsPageOfBottomNavigator(),
LifeStylePageOfBottomNavigator(),
SportsPageOfBottomNavigator()
];
if (_selectedIndex == 0) {
wdgs_option = HomePageForBottomNavigator();
} else if (hi == _selectedIndex) {
wdgs_option = MoviesPageForBottomNavigator();
} else if (){}
List<int Function()> wdgs_option = [
() => HomePageForBottomNavigator(),
() => MoviesPageForBottomNavigator(),
() => ...
];
int val = c[1]();
SingleChildScrollView(
controller: _scrollController,
child: wdgs_option.elementAt(_selectedIndex),
)
SingleChildScrollView(
controller: _scrollController,
child: wdgs_option[_selectedIndex](),
)