futures_screen.dart 235 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553
  1. import 'dart:async';
  2. import 'dart:math' show max, pow;
  3. import 'dart:typed_data';
  4. import 'dart:ui' as ui;
  5. import 'package:flutter/material.dart';
  6. import 'package:flutter/rendering.dart';
  7. import 'package:flutter/services.dart';
  8. import 'package:flutter_riverpod/flutter_riverpod.dart';
  9. import 'package:go_router/go_router.dart';
  10. import 'package:gal/gal.dart';
  11. import 'package:path_provider/path_provider.dart';
  12. import 'package:share_plus/share_plus.dart';
  13. import 'dart:io';
  14. import 'package:qr_flutter/qr_flutter.dart';
  15. import '../../../core/config/app_config.dart';
  16. import '../../../core/l10n/app_localizations.dart';
  17. import '../../../core/network/dio_client.dart';
  18. import '../../../core/theme/app_colors.dart';
  19. import '../../../core/utils/number_format.dart';
  20. import '../../../core/utils/symbol_display.dart';
  21. import '../../../core/utils/top_toast.dart';
  22. import '../../../data/services/auth_service.dart';
  23. import '../../../providers/auth_provider.dart';
  24. import '../../../providers/copy_trading_provider.dart';
  25. import '../../../providers/futures_provider.dart';
  26. import '../../../providers/spot_provider.dart';
  27. import '../../widgets/common/app_refresh_indicator.dart';
  28. import '../../widgets/common/app_shimmer.dart';
  29. import '../../widgets/common/kline_toolbar_icon.dart';
  30. import '../../widgets/common/symbol_picker_sheet.dart';
  31. /// 将仓位 marginMode 字符串(来自后端)映射为 l10n 标签
  32. String _marginModeLabel(String mode, AppLocalizations l10n) {
  33. switch (mode) {
  34. case '分仓':
  35. return l10n.splitMargin;
  36. default:
  37. return l10n.crossMargin;
  38. }
  39. }
  40. /// marginMode → 标签颜色:全仓→蓝,分仓/逐仓→紫
  41. Color _marginModeColor(String mode) {
  42. switch (mode) {
  43. case '分仓':
  44. case '逐仓':
  45. return AppColors.rankPurple;
  46. default:
  47. return AppColors.tagBlue;
  48. }
  49. }
  50. /// 从合约 symbol 提取基础币种名(BTC/USDT → BTC,ETCUSDT → ETC)
  51. String _baseCoin(String sym) {
  52. if (sym.contains('/')) return sym.split('/').first;
  53. return sym.toUpperCase().replaceFirst(RegExp(r'USDT$'), '');
  54. }
  55. /// 未登录时跳转登录页,返回 false 表示操作被拦截
  56. bool _requireLogin(BuildContext context, WidgetRef ref) {
  57. final isLoggedIn = ref.read(isLoggedInProvider);
  58. if (!isLoggedIn) {
  59. context.push('/login');
  60. return false;
  61. }
  62. return true;
  63. }
  64. /// 对齐原型的确认弹窗:上方消息 + 可选红色副文本,下方取消/确定按钮
  65. Future<bool> _showFuturesConfirm(
  66. BuildContext context, {
  67. required String message,
  68. String? subMessage,
  69. String? cancelLabel,
  70. String? confirmLabel,
  71. }) async {
  72. final l10n = AppLocalizations.of(context)!;
  73. final cancel = cancelLabel ?? l10n.cancelLabel;
  74. final confirm = confirmLabel ?? l10n.confirmLabel;
  75. final result = await showDialog<bool>(
  76. context: context,
  77. barrierDismissible: true,
  78. builder: (ctx) {
  79. final cs = Theme.of(ctx).colorScheme;
  80. return Dialog(
  81. shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
  82. backgroundColor: cs.surface,
  83. insetPadding: const EdgeInsets.symmetric(horizontal: 40, vertical: 24),
  84. child: Column(
  85. mainAxisSize: MainAxisSize.min,
  86. children: [
  87. Padding(
  88. padding: const EdgeInsets.fromLTRB(24, 24, 24, 20),
  89. child: Column(
  90. crossAxisAlignment: CrossAxisAlignment.start,
  91. children: [
  92. Text(
  93. message,
  94. style: TextStyle(
  95. color: cs.onSurface,
  96. fontSize: 15,
  97. fontWeight: FontWeight.w600),
  98. ),
  99. if (subMessage != null) ...[
  100. const SizedBox(height: 8),
  101. Text(
  102. subMessage,
  103. style: const TextStyle(
  104. color: AppColors.fall, fontSize: 13, height: 1.5),
  105. ),
  106. ],
  107. ],
  108. ),
  109. ),
  110. Divider(height: 1, thickness: 0.5, color: cs.outline.withAlpha(80)),
  111. IntrinsicHeight(
  112. child: Row(
  113. children: [
  114. Expanded(
  115. child: TextButton(
  116. onPressed: () => Navigator.of(ctx).pop(false),
  117. style: TextButton.styleFrom(
  118. padding: const EdgeInsets.symmetric(vertical: 14),
  119. shape: const RoundedRectangleBorder(
  120. borderRadius: BorderRadius.only(
  121. bottomLeft: Radius.circular(16)),
  122. ),
  123. ),
  124. child: Text(
  125. cancel,
  126. style: TextStyle(
  127. color: cs.onSurface.withAlpha(153), fontSize: 15),
  128. ),
  129. ),
  130. ),
  131. VerticalDivider(
  132. width: 1,
  133. thickness: 0.5,
  134. color: cs.outline.withAlpha(80)),
  135. Expanded(
  136. child: TextButton(
  137. onPressed: () => Navigator.of(ctx).pop(true),
  138. style: TextButton.styleFrom(
  139. padding: const EdgeInsets.symmetric(vertical: 14),
  140. shape: const RoundedRectangleBorder(
  141. borderRadius: BorderRadius.only(
  142. bottomRight: Radius.circular(16)),
  143. ),
  144. ),
  145. child: Text(
  146. confirm,
  147. style: const TextStyle(
  148. color: AppColors.brand,
  149. fontSize: 15,
  150. fontWeight: FontWeight.w700),
  151. ),
  152. ),
  153. ),
  154. ],
  155. ),
  156. ),
  157. ],
  158. ),
  159. );
  160. },
  161. );
  162. return result == true;
  163. }
  164. class FuturesScreen extends ConsumerStatefulWidget {
  165. const FuturesScreen({
  166. super.key,
  167. required this.symbol,
  168. this.showSpotSwitcher = true,
  169. });
  170. final String symbol;
  171. final bool showSpotSwitcher;
  172. @override
  173. ConsumerState<FuturesScreen> createState() => _FuturesScreenState();
  174. }
  175. class _FuturesScreenState extends ConsumerState<FuturesScreen> {
  176. late final ScrollController _scroll;
  177. int _obRowCount = 7;
  178. double _obRowH = 22.0; // 订单薄每行高度(动态计算使左右精确对齐)
  179. double _leftPanelHeight = 490.0; // 左侧面板实测高度
  180. final _orderPanelKey = GlobalKey<_OrderPanelState>();
  181. void _onLeftPanelHeight(double h) {
  182. // countFixedH=150:保守余量,确保 N 行内容不溢出
  183. // rowH = (h - 150) / (2N):让行高略小于最大值,Spacer 吸收余量
  184. const countFixedH = 150.0;
  185. final n = ((h - countFixedH) / 44).floor().clamp(4, 14);
  186. final rh = ((h - 150.0) / (n * 2)).clamp(18.0, 28.0);
  187. if (n != _obRowCount ||
  188. (rh - _obRowH).abs() > 0.1 ||
  189. h != _leftPanelHeight) {
  190. setState(() {
  191. _obRowCount = n;
  192. _obRowH = rh;
  193. _leftPanelHeight = h;
  194. });
  195. }
  196. }
  197. @override
  198. void initState() {
  199. super.initState();
  200. _scroll = ScrollController();
  201. _scroll.addListener(_onScroll);
  202. WidgetsBinding.instance.addPostFrameCallback((_) {
  203. if (!mounted) return;
  204. ref.read(futuresActiveSymbolProvider.notifier).state = widget.symbol;
  205. if (widget.showSpotSwitcher) {
  206. ref.read(lastTradingRouteProvider.notifier).state =
  207. '/futures/${widget.symbol}';
  208. }
  209. });
  210. }
  211. @override
  212. void didUpdateWidget(FuturesScreen oldWidget) {
  213. super.didUpdateWidget(oldWidget);
  214. if (widget.symbol != oldWidget.symbol) {
  215. WidgetsBinding.instance.addPostFrameCallback((_) {
  216. if (!mounted) return;
  217. ref.read(futuresActiveSymbolProvider.notifier).state = widget.symbol;
  218. });
  219. }
  220. }
  221. @override
  222. void dispose() {
  223. _scroll.removeListener(_onScroll);
  224. _scroll.dispose();
  225. super.dispose();
  226. }
  227. Future<void> _pushAndPausePolling(BuildContext context, String path) async {
  228. final notifier = ref.read(futuresProvider(widget.symbol).notifier);
  229. notifier.stopPolling();
  230. await context.push(path);
  231. if (mounted) notifier.resumePolling(widget.symbol);
  232. }
  233. void _onScroll() {
  234. if (_scroll.position.pixels < _scroll.position.maxScrollExtent - 200)
  235. return;
  236. final s = ref.read(futuresProvider(widget.symbol));
  237. if (s.activeTab == FuturesTab.orders) {
  238. ref.read(futuresProvider(widget.symbol).notifier).loadMoreOrders();
  239. }
  240. }
  241. @override
  242. Widget build(BuildContext context) {
  243. final symbol = widget.symbol;
  244. final cs = Theme.of(context).colorScheme;
  245. final l10n = AppLocalizations.of(context)!;
  246. return Scaffold(
  247. appBar: AppBar(
  248. elevation: 0,
  249. toolbarHeight: 44,
  250. titleSpacing: 16,
  251. title: widget.showSpotSwitcher
  252. ? _SpotFuturesTabHeader(
  253. activeIndex: 1,
  254. onTap: (i) {
  255. if (i == 0) {
  256. final spotSym = ref.read(spotActiveSymbolProvider);
  257. context.go('/spot/${spotSym.isNotEmpty ? spotSym : 'BTCUSDT'}');
  258. }
  259. },
  260. )
  261. : Text(
  262. l10n.perpetualContract,
  263. style: TextStyle(
  264. color: cs.onSurface,
  265. fontSize: 17,
  266. fontWeight: FontWeight.w600,
  267. ),
  268. ),
  269. centerTitle: false,
  270. bottom: PreferredSize(
  271. preferredSize: const Size.fromHeight(1),
  272. child: Container(height: 1, color: cs.outline.withAlpha(40)),
  273. ),
  274. actions: [
  275. // K 线图标,点击进入行情详情页
  276. IconButton(
  277. icon: KlineToolbarIcon(color: cs.onSurface.withAlpha(180)),
  278. onPressed: () =>
  279. _pushAndPausePolling(context, '/market/futures/$symbol'),
  280. padding: const EdgeInsets.symmetric(horizontal: 8),
  281. constraints: const BoxConstraints(minWidth: 40, minHeight: 40),
  282. ),
  283. ],
  284. ),
  285. body: Listener(
  286. onPointerDown: (_) => FocusScope.of(context).unfocus(),
  287. child: Builder(builder: (context) {
  288. final isLoading =
  289. ref.watch(futuresProvider(symbol).select((s) => s.isLoading));
  290. if (isLoading) return const _FuturesShimmer();
  291. return AppRefreshIndicator(
  292. onRefresh: () =>
  293. ref.read(futuresProvider(symbol).notifier).refresh(),
  294. child: SingleChildScrollView(
  295. controller: _scroll,
  296. physics: const ClampingScrollPhysics(),
  297. child: Column(
  298. children: [
  299. Row(
  300. crossAxisAlignment: CrossAxisAlignment.start,
  301. children: [
  302. Expanded(
  303. flex: 55,
  304. child: _SizeReporter(
  305. onHeight: _onLeftPanelHeight,
  306. child: DecoratedBox(
  307. decoration: BoxDecoration(
  308. border: Border(
  309. right: BorderSide(
  310. color: cs.outline.withAlpha(40),
  311. width: 1,
  312. ),
  313. ),
  314. ),
  315. child: _OrderPanel(
  316. key: _orderPanelKey,
  317. symbol: symbol,
  318. showSpotSwitcher: widget.showSpotSwitcher,
  319. ),
  320. ),
  321. ),
  322. ),
  323. Expanded(
  324. flex: 45,
  325. child: SizedBox(
  326. height: _leftPanelHeight,
  327. child: RepaintBoundary(
  328. child: _OrderBookPanel(
  329. symbol: symbol,
  330. rowCount: _obRowCount,
  331. rowHeight: _obRowH,
  332. onPriceTap: (price) => _orderPanelKey.currentState
  333. ?.setBookPrice(price),
  334. ),
  335. ),
  336. ),
  337. ),
  338. ],
  339. ),
  340. const SizedBox(height: 8),
  341. _BottomSection(symbol: symbol),
  342. const SizedBox(height: 16),
  343. ],
  344. ),
  345. ),
  346. ); // RefreshIndicator
  347. }), // Builder
  348. ),
  349. );
  350. }
  351. }
  352. class _OrderPanel extends ConsumerStatefulWidget {
  353. const _OrderPanel({
  354. super.key,
  355. required this.symbol,
  356. required this.showSpotSwitcher,
  357. });
  358. final String symbol;
  359. final bool showSpotSwitcher;
  360. @override
  361. ConsumerState<_OrderPanel> createState() => _OrderPanelState();
  362. }
  363. class _OrderPanelState extends ConsumerState<_OrderPanel> {
  364. final _priceController = TextEditingController();
  365. final _amountController = TextEditingController();
  366. final _triggerPriceController = TextEditingController();
  367. final _tpController = TextEditingController();
  368. final _slController = TextEditingController();
  369. bool _updatingFromSlider = false;
  370. bool _priceFilled = false; // 是否已完成首次价格回显
  371. double _lastPrice = 0; // 最新价缓存,用 ref.listen 维护,不触发 rebuild
  372. // 可开多/开空最大值快照
  373. String _maxOpenAmt = '--';
  374. // 市价单:每 5 秒自动刷新最大可开量
  375. Timer? _marketRefreshTimer;
  376. // 监听路由 secondaryAnimation,导航返回时清除焦点
  377. Animation<double>? _secondaryAnim;
  378. bool _isCoveredByRoute = false;
  379. @override
  380. void initState() {
  381. super.initState();
  382. _amountController.addListener(_onAmountChanged);
  383. // 进入页面后首帧快照最大可开量,并根据当前下单类型决定是否启动定时器
  384. WidgetsBinding.instance.addPostFrameCallback((_) {
  385. if (!mounted) return;
  386. _refreshMaxAmount();
  387. _updateMarketTimer();
  388. });
  389. // 价格输入框变化时(非市价单)刷新最大可开量
  390. _priceController.addListener(_onPriceChanged);
  391. _triggerPriceController.addListener(_onPriceChanged);
  392. }
  393. void _onPriceChanged() {
  394. final s = ref.read(futuresProvider(widget.symbol));
  395. if (s.orderType != OrderType.market) _refreshMaxAmount();
  396. }
  397. void _refreshMaxAmount() {
  398. if (!mounted) return;
  399. final s = ref.read(futuresProvider(widget.symbol));
  400. setState(() {
  401. _maxOpenAmt = _calcMaxOpenAmount(s);
  402. });
  403. }
  404. /// 市价单开启 5 秒定时刷新,其他类型取消定时器(由价格输入框变化驱动)
  405. void _updateMarketTimer() {
  406. final s = ref.read(futuresProvider(widget.symbol));
  407. if (s.orderType == OrderType.market) {
  408. _marketRefreshTimer ??= Timer.periodic(
  409. const Duration(seconds: 5), (_) => _refreshMaxAmount());
  410. } else {
  411. _marketRefreshTimer?.cancel();
  412. _marketRefreshTimer = null;
  413. }
  414. }
  415. @override
  416. void didChangeDependencies() {
  417. super.didChangeDependencies();
  418. final anim = ModalRoute.of(context)?.secondaryAnimation;
  419. if (anim != _secondaryAnim) {
  420. _secondaryAnim?.removeStatusListener(_onSecondaryAnimation);
  421. _secondaryAnim = anim;
  422. _secondaryAnim?.addStatusListener(_onSecondaryAnimation);
  423. }
  424. }
  425. void _onSecondaryAnimation(AnimationStatus status) {
  426. if (status == AnimationStatus.forward ||
  427. status == AnimationStatus.completed) {
  428. _isCoveredByRoute = true;
  429. } else if (status == AnimationStatus.dismissed && _isCoveredByRoute) {
  430. _isCoveredByRoute = false;
  431. // postFrameCallback 确保在 Flutter 自动恢复焦点之后再清除
  432. WidgetsBinding.instance.addPostFrameCallback((_) {
  433. if (mounted) FocusManager.instance.primaryFocus?.unfocus();
  434. });
  435. }
  436. }
  437. @override
  438. void didUpdateWidget(_OrderPanel oldWidget) {
  439. super.didUpdateWidget(oldWidget);
  440. if (oldWidget.symbol != widget.symbol) {
  441. // 切换币对:延迟到下一帧再清空,重置首次价格回显标记
  442. _priceFilled = false;
  443. WidgetsBinding.instance.addPostFrameCallback((_) {
  444. if (!mounted) return;
  445. _priceController.clear();
  446. _amountController.clear();
  447. _triggerPriceController.clear();
  448. _tpController.clear();
  449. _slController.clear();
  450. });
  451. }
  452. }
  453. void _onAmountChanged() {
  454. if (_updatingFromSlider) return;
  455. final state = ref.read(futuresProvider(widget.symbol));
  456. final amount = double.tryParse(_amountController.text.replaceAll(',', ''));
  457. final notifier = ref.read(futuresProvider(widget.symbol).notifier);
  458. if (amount == null || amount <= 0) {
  459. notifier.setSliderPercentFromInput(0);
  460. return;
  461. }
  462. final refPrice = _refPrice(state);
  463. // 限价/计划委托未填价格时,滑块归零但不弹 toast(toast 在点下单时才提示)
  464. if (refPrice <= 0) {
  465. notifier.setSliderPercentFromInput(0);
  466. return;
  467. }
  468. final contractSize = state.contractSize > 0 ? state.contractSize : 1.0;
  469. // ── 平仓模式:以仓位可平量(BTC)为 max ──
  470. if (state.positionMode == PositionMode.close) {
  471. final maxBtc = _closeMaxBtc(state);
  472. if (maxBtc <= 0) return;
  473. final double pct;
  474. switch (state.amountUnit) {
  475. case AmountUnit.btc:
  476. pct = (amount / maxBtc).clamp(0.0, 1.0);
  477. case AmountUnit.usdt:
  478. final maxUsdt = maxBtc * refPrice;
  479. pct = maxUsdt > 0 ? (amount / maxUsdt).clamp(0.0, 1.0) : 0.0;
  480. case AmountUnit.lots:
  481. final maxLots = contractSize > 0 && refPrice > 0
  482. ? maxBtc * refPrice / contractSize
  483. : 0.0;
  484. pct = maxLots > 0 ? (amount / maxLots).clamp(0.0, 1.0) : 0.0;
  485. }
  486. notifier.setSliderPercentFromInput(pct);
  487. return;
  488. }
  489. // ── 开仓模式:以可用保证金为 max ──
  490. final availableMargin = state.accountInfo.availableMargin;
  491. final leverage = state.leverage;
  492. if (availableMargin <= 0 || refPrice <= 0) return;
  493. // maxNotional = 最大名义仓位价值(保证金 × 杠杆)
  494. final maxNotional = availableMargin * leverage;
  495. if (maxNotional <= 0) return;
  496. final double pct;
  497. switch (state.amountUnit) {
  498. case AmountUnit.lots:
  499. if (contractSize <= 0) return;
  500. final maxL = (maxNotional / contractSize).floor();
  501. pct = maxL > 0 ? (amount / maxL).clamp(0.0, 1.0) : 0.0;
  502. case AmountUnit.usdt:
  503. pct = (amount / maxNotional).clamp(0.0, 1.0);
  504. case AmountUnit.btc:
  505. pct = (amount * refPrice / maxNotional).clamp(0.0, 1.0);
  506. }
  507. notifier.setSliderPercentFromInput(pct);
  508. }
  509. /// 计算数量上限时使用的参考价格。
  510. /// 返回 0 表示必填价格未填,调用方应提示用户先输入价格。
  511. /// 市价 → 最新成交价
  512. /// 限价 / 计划限价 → 价格输入框(未填返回 0)
  513. /// 计划市价 → 触发价输入框(未填返回 0)
  514. double _refPrice(FuturesState state) {
  515. switch (state.orderType) {
  516. case OrderType.market:
  517. return state.lastPrice;
  518. case OrderType.limit:
  519. case OrderType.conditionalLimit:
  520. final v = double.tryParse(_priceController.text.replaceAll(',', ''));
  521. return (v != null && v > 0) ? v : 0.0;
  522. case OrderType.conditionalMarket:
  523. final v =
  524. double.tryParse(_triggerPriceController.text.replaceAll(',', ''));
  525. return (v != null && v > 0) ? v : 0.0;
  526. }
  527. }
  528. /// 检查参考价格是否有效,无效时弹出提示并返回 false
  529. bool _checkRefPrice(BuildContext context, FuturesState state) {
  530. if (_refPrice(state) > 0) return true;
  531. final l10n = AppLocalizations.of(context)!;
  532. final hint = state.orderType == OrderType.conditionalMarket
  533. ? l10n.enterTriggerPrice
  534. : l10n.enterPrice;
  535. showTopToast(context, message: hint, backgroundColor: AppColors.fall);
  536. return false;
  537. }
  538. /// 当前符合 symbol 的最大可平量(单位:BTC/基础币),取多空中较大的一方
  539. double _closeMaxBtc(FuturesState state) {
  540. final normSym =
  541. state.symbol.replaceAll('/', '').replaceAll('-', '').toUpperCase();
  542. return state.positions
  543. .where((p) => p.symbol.replaceAll('/', '').toUpperCase() == normSym)
  544. .fold(0.0, (m, p) => p.availableSize > m ? p.availableSize : m);
  545. }
  546. @override
  547. void dispose() {
  548. _secondaryAnim?.removeStatusListener(_onSecondaryAnimation);
  549. _amountController.removeListener(_onAmountChanged);
  550. _priceController.removeListener(_onPriceChanged);
  551. _triggerPriceController.removeListener(_onPriceChanged);
  552. _marketRefreshTimer?.cancel();
  553. _priceController.dispose();
  554. _amountController.dispose();
  555. _triggerPriceController.dispose();
  556. _tpController.dispose();
  557. _slController.dispose();
  558. super.dispose();
  559. }
  560. /// 订单薄点击回调:将价格填入对应输入框
  561. /// 计划市价 → 回显到触发价格;其余情况(含计划限价)→ 回显到委托价格
  562. void setBookPrice(double price) {
  563. if (!mounted) return;
  564. final state = ref.read(futuresProvider(widget.symbol));
  565. final precision = state.pricePrecision;
  566. final formatted = price.toStringAsFixed(precision);
  567. if (state.orderType == OrderType.conditionalMarket) {
  568. _triggerPriceController.text = formatted;
  569. } else {
  570. _priceController.text = formatted;
  571. }
  572. }
  573. @override
  574. Widget build(BuildContext context) {
  575. final cs = Theme.of(context).colorScheme;
  576. final provider = futuresProvider(widget.symbol);
  577. final notifier = ref.read(provider.notifier);
  578. // 切换开仓/平仓模式时,清空数量输入框和滑块
  579. ref.listen(provider.select((s) => s.positionMode), (prev, next) {
  580. if (prev != next) {
  581. WidgetsBinding.instance.addPostFrameCallback((_) {
  582. if (!mounted) return;
  583. _amountController.clear();
  584. _priceController.clear();
  585. notifier.setSliderPercent(0);
  586. });
  587. }
  588. });
  589. // 切换下单类型时,清空所有输入框和滑块;
  590. // 重置 _priceFilled,限价/计划限价会在下一帧自动回显最新价;
  591. // 同时重新快照最大可开量
  592. ref.listen(provider.select((s) => s.orderType), (prev, next) {
  593. if (prev != next) {
  594. _priceFilled = false;
  595. WidgetsBinding.instance.addPostFrameCallback((_) {
  596. if (!mounted) return;
  597. FocusManager.instance.primaryFocus?.unfocus();
  598. _priceController.clear();
  599. _amountController.clear();
  600. _triggerPriceController.clear();
  601. _tpController.clear();
  602. _slController.clear();
  603. notifier.setSliderPercent(0);
  604. _refreshMaxAmount();
  605. _updateMarketTimer();
  606. });
  607. }
  608. });
  609. // 账户数据加载完成时刷新最大可开量(进入页面时账户信息可能尚未到达)
  610. ref.listen(provider.select((s) => s.accountInfo.availableMargin),
  611. (prev, next) {
  612. if (prev != next) _refreshMaxAmount();
  613. });
  614. // 最新价:仅缓存到字段,不触发 rebuild(消除每 ~120ms 一次的整面板重建)
  615. // _priceFilled 逻辑也移到此处
  616. ref.listen<double>(provider.select((s) => s.lastPrice), (_, next) {
  617. _lastPrice = next;
  618. if (!_priceFilled && next > 0) {
  619. _priceFilled = true;
  620. final precision = ref.read(provider).pricePrecision;
  621. WidgetsBinding.instance.addPostFrameCallback((_) {
  622. if (!mounted) return;
  623. if (_priceController.text.isEmpty) {
  624. _priceController.text = next.toStringAsFixed(precision);
  625. }
  626. });
  627. }
  628. });
  629. // 首次 build 时同步一次(ref.listen 不回调当前值)
  630. if (_lastPrice == 0) {
  631. _lastPrice = ref.read(provider).lastPrice;
  632. if (!_priceFilled && _lastPrice > 0) {
  633. _priceFilled = true;
  634. WidgetsBinding.instance.addPostFrameCallback((_) {
  635. if (!mounted) return;
  636. if (_priceController.text.isEmpty) {
  637. _priceController.text =
  638. _lastPrice.toStringAsFixed(ref.read(provider).pricePrecision);
  639. }
  640. });
  641. }
  642. }
  643. final change24h = ref.watch(provider.select((s) => s.change24h));
  644. final isConditionalOrder =
  645. ref.watch(provider.select((s) => s.isConditionalOrder));
  646. final showPriceInput = ref.watch(provider.select((s) => s.showPriceInput));
  647. final isMarketOrder =
  648. ref.watch(provider.select((s) => s.orderType == OrderType.market));
  649. final amountUnit = ref.watch(provider.select((s) => s.amountUnit));
  650. final amountUnitLabelRaw =
  651. ref.watch(provider.select((s) => s.amountUnitLabel));
  652. final sliderPercent = ref.watch(provider.select((s) => s.sliderPercent));
  653. final tpslEnabled = ref.watch(provider.select((s) => s.tpslEnabled));
  654. final leverage = ref.watch(provider.select((s) => s.leverage));
  655. final availableMargin =
  656. ref.watch(provider.select((s) => s.accountInfo.availableMargin));
  657. final positionMode = ref.watch(provider.select((s) => s.positionMode));
  658. final isClose = positionMode == PositionMode.close;
  659. final coinPrecision = ref.watch(provider.select((s) => s.coinPrecision));
  660. final normSym =
  661. widget.symbol.replaceAll('/', '').replaceAll('-', '').toUpperCase();
  662. final longAvail = ref.watch(provider.select((s) => s.positions
  663. .where((p) =>
  664. p.symbol.replaceAll('/', '').toUpperCase() == normSym &&
  665. p.side == OrderSide.long)
  666. .fold(0.0, (v, p) => v + p.availableSize)));
  667. final shortAvail = ref.watch(provider.select((s) => s.positions
  668. .where((p) =>
  669. p.symbol.replaceAll('/', '').toUpperCase() == normSym &&
  670. p.side == OrderSide.short)
  671. .fold(0.0, (v, p) => v + p.availableSize)));
  672. final coinSymbol = _baseCoin(widget.symbol);
  673. final pricePrecision = ref.watch(provider.select((s) => s.pricePrecision));
  674. final amountPrecision =
  675. ref.watch(provider.select((s) => s.currentAmountPrecision));
  676. final priceFormatter = _PrecisionInputFormatter(pricePrecision);
  677. final amountFormatter = _PrecisionInputFormatter(amountPrecision);
  678. final isLoggedIn = ref.watch(isLoggedInProvider);
  679. final isSwitchingMode =
  680. ref.watch(provider.select((s) => s.isSwitchingMode));
  681. final marginMode = ref.watch(provider.select((s) => s.marginMode));
  682. // ── 高频复用样式(每次 rebuild 计算一次,复用 N 次)─────────
  683. final labelStyle =
  684. TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 11);
  685. final valueStyle = TextStyle(
  686. color: cs.onSurface, fontSize: 11, fontWeight: FontWeight.w600);
  687. return Padding(
  688. padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
  689. child: Column(
  690. crossAxisAlignment: CrossAxisAlignment.start,
  691. children: [
  692. // ── Symbol row(v2:在左侧表单内)──────────────
  693. GestureDetector(
  694. onTap: () => _showSymbolPicker(context),
  695. behavior: HitTestBehavior.opaque,
  696. child: Padding(
  697. padding: const EdgeInsets.only(bottom: 4),
  698. child: Row(
  699. mainAxisSize: MainAxisSize.min,
  700. children: [
  701. Flexible(
  702. child: Text(
  703. formatUsdtPairDisplay(widget.symbol),
  704. overflow: TextOverflow.ellipsis,
  705. style: TextStyle(
  706. color: cs.onSurface,
  707. fontSize: 17,
  708. fontWeight: FontWeight.w700),
  709. ),
  710. ),
  711. Icon(Icons.keyboard_arrow_down,
  712. color: cs.onSurface.withAlpha(153), size: 16),
  713. const SizedBox(width: 6),
  714. Text(
  715. formatChange(change24h),
  716. style: TextStyle(
  717. color: AppColors.changeColor(change24h),
  718. fontSize: 12,
  719. fontWeight: FontWeight.w500,
  720. fontFeatures: const [FontFeature.tabularFigures()]),
  721. ),
  722. ],
  723. ),
  724. ),
  725. ),
  726. const SizedBox(height: 8),
  727. _MarginLeverageRow(symbol: widget.symbol),
  728. const SizedBox(height: 10),
  729. // TODO: 平仓 tab 功能暂时隐藏,待接口完善后恢复
  730. // _PositionModePills(symbol: widget.symbol),
  731. // const SizedBox(height: 10),
  732. _OrderTypeDropdown(symbol: widget.symbol),
  733. const SizedBox(height: 8),
  734. if (isConditionalOrder) ...[
  735. _LargeInput(
  736. controller: _triggerPriceController,
  737. label: AppLocalizations.of(context)!.triggerPrice,
  738. unit: 'USDT',
  739. suffixDropdown: AppLocalizations.of(context)!.markLabel,
  740. inputFormatters: [priceFormatter],
  741. ),
  742. const SizedBox(height: 8),
  743. ],
  744. if (isMarketOrder) ...[
  745. // 市价委托:显示只读"市价"占位框
  746. Builder(builder: (context) {
  747. final cs = Theme.of(context).colorScheme;
  748. return Container(
  749. height: 52,
  750. decoration: BoxDecoration(
  751. color: cs.onSurface.withAlpha(8),
  752. borderRadius: BorderRadius.circular(8),
  753. ),
  754. padding: const EdgeInsets.symmetric(horizontal: 12),
  755. child: Row(
  756. children: [
  757. Expanded(
  758. child: Text(
  759. AppLocalizations.of(context)!.marketPrice,
  760. style: TextStyle(
  761. color: cs.onSurface,
  762. fontSize: 15,
  763. fontWeight: FontWeight.w500,
  764. ),
  765. ),
  766. ),
  767. Text(
  768. 'USDT',
  769. style: TextStyle(
  770. color: cs.onSurface.withAlpha(100),
  771. fontSize: 13,
  772. ),
  773. ),
  774. ],
  775. ),
  776. );
  777. }),
  778. const SizedBox(height: 8),
  779. ] else if (showPriceInput) ...[
  780. _LargeInput(
  781. controller: _priceController,
  782. label: AppLocalizations.of(context)!.priceLabel2,
  783. unit: 'USDT',
  784. inputFormatters: [priceFormatter],
  785. ),
  786. const SizedBox(height: 8),
  787. ],
  788. // ── 数量输入 ──
  789. _LargeInput(
  790. key: const ValueKey('amount_input'),
  791. controller: _amountController,
  792. label: AppLocalizations.of(context)!.quantityLabel,
  793. unit: amountUnit == AmountUnit.lots
  794. ? AppLocalizations.of(context)!.lotsLabel
  795. : amountUnitLabelRaw,
  796. showUnitDropdown: true,
  797. onUnitTap: () => _showAmountUnitSheet(context, notifier),
  798. inputFormatters: [amountFormatter],
  799. ),
  800. const SizedBox(height: 10),
  801. // ── 百分比滑动条 ──
  802. _PercentSlider(
  803. percent: sliderPercent,
  804. enabled: true,
  805. onChanged: (pct) {
  806. // 始终从 ref.read 取最新状态,避免闭包捕获旧值导致联动失效
  807. final s = ref.read(futuresProvider(widget.symbol));
  808. // 限价/计划委托未填价格时拦截,提示用户
  809. if (pct > 0 && !_checkRefPrice(context, s)) return;
  810. notifier.setSliderPercent(pct);
  811. _updatingFromSlider = true;
  812. if (pct == 0) {
  813. _amountController.clear();
  814. } else {
  815. final contractSize = s.contractSize > 0 ? s.contractSize : 1.0;
  816. final curPrice = _refPrice(s);
  817. // ── 平仓模式:以仓位可平量(BTC)为基准 ──
  818. if (s.positionMode == PositionMode.close) {
  819. final maxBtc = _closeMaxBtc(s);
  820. if (maxBtc > 0) {
  821. switch (s.amountUnit) {
  822. case AmountUnit.btc:
  823. final rawBtcClose = maxBtc * pct;
  824. final btcCloseFactor =
  825. pow(10, s.coinPrecision).toDouble();
  826. final truncBtcClose =
  827. (rawBtcClose * btcCloseFactor).truncateToDouble() /
  828. btcCloseFactor;
  829. _amountController.text =
  830. truncBtcClose.toStringAsFixed(s.coinPrecision);
  831. case AmountUnit.usdt:
  832. final rawCloseUsdt = maxBtc * curPrice * pct;
  833. final closeDisplayDp =
  834. s.usdtPrecision < 2 ? s.usdtPrecision : 2;
  835. final closeFactor = pow(10, closeDisplayDp).toDouble();
  836. final flooredCloseUsdt =
  837. (rawCloseUsdt * closeFactor).floor() / closeFactor;
  838. _amountController.text =
  839. flooredCloseUsdt.toStringAsFixed(closeDisplayDp);
  840. case AmountUnit.lots:
  841. if (contractSize > 0 && curPrice > 0) {
  842. final maxLots = maxBtc * curPrice / contractSize;
  843. final lots = maxLots * pct;
  844. _amountController.text = s.volScale > 0
  845. ? lots.toStringAsFixed(s.volScale)
  846. : lots.floor().toString();
  847. }
  848. }
  849. }
  850. } else {
  851. // ── 开仓模式:以可用保证金为基准 ──
  852. final curMargin = s.accountInfo.availableMargin;
  853. final curLeverage = s.leverage;
  854. if (curMargin > 0 && curPrice > 0) {
  855. final feeMultiplier = 1 + s.openFeeRate * curLeverage;
  856. final effectiveMargin = curMargin / feeMultiplier * pct;
  857. final maxNotional = effectiveMargin * curLeverage;
  858. switch (s.amountUnit) {
  859. case AmountUnit.usdt:
  860. final displayDp =
  861. s.usdtPrecision < 2 ? s.usdtPrecision : 2;
  862. final factor = pow(10, displayDp).toDouble();
  863. final flooredUsdt =
  864. (maxNotional * factor).floor() / factor;
  865. _amountController.text =
  866. flooredUsdt.toStringAsFixed(displayDp);
  867. case AmountUnit.btc:
  868. final rawBtcOpen = maxNotional / curPrice;
  869. final btcOpenFactor =
  870. pow(10, s.coinPrecision).toDouble();
  871. final truncBtcOpen =
  872. (rawBtcOpen * btcOpenFactor).truncateToDouble() /
  873. btcOpenFactor;
  874. _amountController.text =
  875. truncBtcOpen.toStringAsFixed(s.coinPrecision);
  876. case AmountUnit.lots:
  877. if (contractSize <= 0) break;
  878. final maxL =
  879. (effectiveMargin * curLeverage / contractSize)
  880. .floor();
  881. _amountController.text = s.volScale > 0
  882. ? maxL.toStringAsFixed(s.volScale)
  883. : maxL.toString();
  884. }
  885. }
  886. }
  887. }
  888. _updatingFromSlider = false;
  889. },
  890. ),
  891. ...[
  892. const SizedBox(height: 10),
  893. Row(
  894. children: [
  895. Text('${AppLocalizations.of(context)!.availableLabel} ',
  896. style: TextStyle(
  897. color: cs.onSurface.withAlpha(153), fontSize: 12)),
  898. Text(
  899. '${formatAmount(availableMargin)} USDT',
  900. style: TextStyle(
  901. color: cs.onSurface,
  902. fontSize: 12,
  903. fontWeight: FontWeight.w600),
  904. ),
  905. const Spacer(),
  906. GestureDetector(
  907. onTap: () async {
  908. final notifier =
  909. ref.read(futuresProvider(widget.symbol).notifier);
  910. notifier.stopPolling();
  911. await context.push('/asset/transfer');
  912. if (context.mounted) notifier.resumePolling(widget.symbol);
  913. },
  914. child: Icon(Icons.swap_horiz,
  915. color: cs.onSurface.withAlpha(153), size: 16),
  916. ),
  917. ],
  918. ),
  919. const SizedBox(height: 6),
  920. ],
  921. // 可开多 + 保证金(开多按钮上方)
  922. if (isLoggedIn && !isClose) ...[
  923. Row(children: [
  924. Text('${AppLocalizations.of(context)!.canOpenLong} ',
  925. style: labelStyle),
  926. Flexible(
  927. child: Text('$_maxOpenAmt $amountUnitLabelRaw',
  928. style: valueStyle, overflow: TextOverflow.ellipsis)),
  929. ]),
  930. const SizedBox(height: 2),
  931. ListenableBuilder(
  932. listenable: Listenable.merge([
  933. _priceController,
  934. _amountController,
  935. _triggerPriceController
  936. ]),
  937. builder: (context, _) {
  938. final marginStr = _calcMargin(_lastPrice, leverage);
  939. return Text(
  940. AppLocalizations.of(context)!.marginBalance(marginStr),
  941. style: labelStyle);
  942. },
  943. ),
  944. const SizedBox(height: 6),
  945. ],
  946. SizedBox(
  947. width: double.infinity,
  948. height: 40,
  949. child: ElevatedButton(
  950. onPressed: isSwitchingMode
  951. ? null
  952. : isLoggedIn
  953. ? () => isClose
  954. ? _closeOrder(context, notifier, OrderSide.long)
  955. : _placeOrder(context, notifier, OrderSide.long)
  956. : () => context.push('/login'),
  957. style: ElevatedButton.styleFrom(
  958. backgroundColor: isClose ? AppColors.fall : AppColors.rise,
  959. shape: RoundedRectangleBorder(
  960. borderRadius: BorderRadius.circular(8)),
  961. elevation: 0,
  962. ),
  963. child: Text(
  964. isClose
  965. ? AppLocalizations.of(context)!.closeLong
  966. : AppLocalizations.of(context)!.openLong,
  967. style: const TextStyle(
  968. color: Colors.white,
  969. fontSize: 15,
  970. fontWeight: FontWeight.w600),
  971. ),
  972. ),
  973. ),
  974. const SizedBox(height: 8),
  975. // 可开空 + 保证金(开空按钮上方)
  976. if (isLoggedIn && !isClose) ...[
  977. Row(children: [
  978. Text('${AppLocalizations.of(context)!.canOpenShort} ',
  979. style: labelStyle),
  980. Flexible(
  981. child: Text('$_maxOpenAmt $amountUnitLabelRaw',
  982. style: valueStyle, overflow: TextOverflow.ellipsis)),
  983. ]),
  984. const SizedBox(height: 2),
  985. ListenableBuilder(
  986. listenable: Listenable.merge([
  987. _priceController,
  988. _amountController,
  989. _triggerPriceController
  990. ]),
  991. builder: (context, _) {
  992. final marginStr = _calcMargin(_lastPrice, leverage);
  993. return Text(
  994. AppLocalizations.of(context)!.marginBalance(marginStr),
  995. style: labelStyle);
  996. },
  997. ),
  998. const SizedBox(height: 6),
  999. ],
  1000. SizedBox(
  1001. width: double.infinity,
  1002. height: 40,
  1003. child: ElevatedButton(
  1004. onPressed: isSwitchingMode
  1005. ? null
  1006. : isLoggedIn
  1007. ? () => isClose
  1008. ? _closeOrder(context, notifier, OrderSide.short)
  1009. : _placeOrder(context, notifier, OrderSide.short)
  1010. : () => context.push('/login'),
  1011. style: ElevatedButton.styleFrom(
  1012. backgroundColor: isClose ? AppColors.rise : AppColors.fall,
  1013. shape: RoundedRectangleBorder(
  1014. borderRadius: BorderRadius.circular(8)),
  1015. elevation: 0,
  1016. ),
  1017. child: Text(
  1018. isClose
  1019. ? AppLocalizations.of(context)!.closeShort
  1020. : AppLocalizations.of(context)!.openShort,
  1021. style: const TextStyle(
  1022. color: Colors.white,
  1023. fontSize: 15,
  1024. fontWeight: FontWeight.w600),
  1025. ),
  1026. ),
  1027. ),
  1028. const SizedBox(height: 12),
  1029. ],
  1030. ),
  1031. );
  1032. }
  1033. Future<void> _placeOrder(
  1034. BuildContext context, FuturesNotifier notifier, OrderSide side) async {
  1035. if (!_requireLogin(context, ref)) return;
  1036. // formatPrice 会加千分符,解析时需先去掉逗号
  1037. final price = double.tryParse(_priceController.text.replaceAll(',', ''));
  1038. final amount = double.tryParse(_amountController.text.replaceAll(',', ''));
  1039. final triggerPrice =
  1040. double.tryParse(_triggerPriceController.text.replaceAll(',', ''));
  1041. final tpPrice = double.tryParse(_tpController.text.replaceAll(',', ''));
  1042. final slPrice = double.tryParse(_slController.text.replaceAll(',', ''));
  1043. final err = await notifier.placeOpenOrder(
  1044. side: side,
  1045. entrustPrice: price,
  1046. triggerPrice: triggerPrice,
  1047. volume: amount,
  1048. tpPrice: tpPrice,
  1049. slPrice: slPrice,
  1050. );
  1051. if (!context.mounted) return;
  1052. if (err == null) {
  1053. // 下单成功后清空输入框
  1054. _priceController.clear();
  1055. _amountController.clear();
  1056. _triggerPriceController.clear();
  1057. _tpController.clear();
  1058. _slController.clear();
  1059. notifier.setSliderPercent(0);
  1060. }
  1061. final l10n0 = AppLocalizations.of(context)!;
  1062. showTopToast(context,
  1063. message: err != null
  1064. ? (resolveProviderError(err, l10n0) ?? err)
  1065. : l10n0.orderSuccess,
  1066. backgroundColor: err != null ? AppColors.fall : AppColors.rise);
  1067. }
  1068. Future<void> _closeOrder(
  1069. BuildContext context, FuturesNotifier notifier, OrderSide side) async {
  1070. if (!_requireLogin(context, ref)) return;
  1071. final price = double.tryParse(_priceController.text.replaceAll(',', ''));
  1072. final triggerPrice =
  1073. double.tryParse(_triggerPriceController.text.replaceAll(',', ''));
  1074. // 将用户输入量转为基础币(BTC)后传入;0/null 表示全仓平
  1075. final inputAmount =
  1076. double.tryParse(_amountController.text.replaceAll(',', ''));
  1077. final s = ref.read(futuresProvider(widget.symbol));
  1078. final double? volumeInBtc;
  1079. if (inputAmount != null && inputAmount > 0) {
  1080. final cs = s.contractSize > 0 ? s.contractSize : 1.0;
  1081. final isMarketClose = s.orderType == OrderType.market;
  1082. final ep =
  1083. (!isMarketClose && price != null && price > 0) ? price : s.lastPrice;
  1084. volumeInBtc = switch (s.amountUnit) {
  1085. AmountUnit.btc => inputAmount,
  1086. AmountUnit.usdt => ep > 0 ? inputAmount / ep : null,
  1087. AmountUnit.lots => ep > 0 ? inputAmount * cs / ep : null,
  1088. };
  1089. } else {
  1090. volumeInBtc = null; // 全仓平
  1091. }
  1092. final isConditional = s.orderType == OrderType.conditionalMarket ||
  1093. s.orderType == OrderType.conditionalLimit;
  1094. String? err;
  1095. if (isConditional && triggerPrice != null && triggerPrice > 0) {
  1096. err = await notifier.closeConditionalByDirection(
  1097. side,
  1098. triggerPrice: triggerPrice,
  1099. volume: volumeInBtc,
  1100. entrustPrice: (price != null && price > 0) ? price : 0,
  1101. );
  1102. } else {
  1103. final isMarket = s.orderType == OrderType.market;
  1104. err = await notifier.closeByDirection(
  1105. side,
  1106. price: isMarket ? null : price,
  1107. volume: volumeInBtc,
  1108. );
  1109. }
  1110. if (!context.mounted) return;
  1111. if (err == null) {
  1112. _amountController.clear();
  1113. _triggerPriceController.clear();
  1114. notifier.setSliderPercent(0);
  1115. }
  1116. final l10n1 = AppLocalizations.of(context)!;
  1117. showTopToast(context,
  1118. message: resolveProviderError(err, l10n1) ?? l10n1.closeOrderSubmitted,
  1119. backgroundColor: err != null ? AppColors.fall : AppColors.rise);
  1120. }
  1121. String _calcMargin(double lastPrice, double leverage) {
  1122. final state = ref.read(futuresProvider(widget.symbol));
  1123. // 计划市价用触发价,计划限价/限价用价格输入框,市价用最新价
  1124. final double price;
  1125. if (state.orderType == OrderType.conditionalMarket) {
  1126. price =
  1127. double.tryParse(_triggerPriceController.text.replaceAll(',', '')) ??
  1128. lastPrice;
  1129. } else {
  1130. price = double.tryParse(_priceController.text.replaceAll(',', '')) ??
  1131. lastPrice;
  1132. }
  1133. final amount =
  1134. double.tryParse(_amountController.text.replaceAll(',', '')) ?? 0;
  1135. if (amount == 0 || leverage == 0) return '0.00';
  1136. final contractSize = state.contractSize > 0 ? state.contractSize : 1.0;
  1137. // 换算为 USDT 名义价值再除以杠杆
  1138. // 张: lots × contractSize(USDT/张) = USDT(面值已是 USDT,无需再乘价格)
  1139. // USDT: 直接
  1140. // BTC/ETH/ETC: 数量 × price = USDT
  1141. final availableMargin =
  1142. ref.read(futuresProvider(widget.symbol)).accountInfo.availableMargin;
  1143. final double rawMargin;
  1144. switch (state.amountUnit) {
  1145. case AmountUnit.usdt:
  1146. // USDT 输入为名义仓位价值,除以杠杆得保证金
  1147. rawMargin = amount / leverage;
  1148. case AmountUnit.lots:
  1149. // 张 × contractSize = 名义价值,再除杠杆得保证金
  1150. rawMargin = amount * contractSize / leverage;
  1151. case AmountUnit.btc:
  1152. // 基础币 × 价格 = 名义价值,再除杠杆得保证金
  1153. rawMargin = amount * price / leverage;
  1154. }
  1155. // clamp 后再截断(floor),防止 formatAmount 进位后显示值 > 可用
  1156. final clamped =
  1157. availableMargin > 0 ? rawMargin.clamp(0.0, availableMargin) : rawMargin;
  1158. final margin = (clamped * 100).floorToDouble() / 100;
  1159. return formatAmount(margin, decimals: 2);
  1160. }
  1161. /// 可开多/可开空数量,与老版 Android 公式一致:
  1162. /// availableBalance / (((1/leverage) + openFee) * lastPrice)
  1163. String _calcMaxOpenAmount(FuturesState state) {
  1164. final refPrice = _refPrice(state);
  1165. final avail = state.accountInfo.availableMargin;
  1166. final leverage = state.leverage;
  1167. final cs = state.contractSize > 0 ? state.contractSize : 1.0;
  1168. if (avail <= 0 || refPrice <= 0) return '--';
  1169. final feeMultiplier = 1 + state.openFeeRate * leverage;
  1170. final maxNotional = avail / feeMultiplier * leverage;
  1171. switch (state.amountUnit) {
  1172. case AmountUnit.usdt:
  1173. return formatAmount(maxNotional);
  1174. case AmountUnit.lots:
  1175. return (maxNotional / cs).floor().toString();
  1176. case AmountUnit.btc:
  1177. return formatAmount(maxNotional / refPrice,
  1178. decimals: state.coinPrecision);
  1179. }
  1180. }
  1181. /// 可平量(基于仓位可平 size,换算为当前单位)
  1182. String _calcMaxCloseAmount(FuturesState state, double availSize) {
  1183. final refPrice = _refPrice(state);
  1184. final cs = state.contractSize > 0 ? state.contractSize : 1.0;
  1185. switch (state.amountUnit) {
  1186. case AmountUnit.btc:
  1187. return formatAmount(availSize, decimals: state.coinPrecision);
  1188. case AmountUnit.usdt:
  1189. return refPrice > 0 ? formatAmount(availSize * refPrice) : '--';
  1190. case AmountUnit.lots:
  1191. return (cs > 0 && refPrice > 0)
  1192. ? (availSize * refPrice / cs).floor().toString()
  1193. : '--';
  1194. }
  1195. }
  1196. void _showSymbolPicker(BuildContext context) {
  1197. FocusScope.of(context).unfocus();
  1198. final targetBasePath = widget.showSpotSwitcher ? '/futures' : '/contracts';
  1199. showModalBottomSheet<void>(
  1200. context: context,
  1201. useRootNavigator: true,
  1202. isScrollControlled: true,
  1203. backgroundColor: Theme.of(context).colorScheme.surface,
  1204. shape: const RoundedRectangleBorder(
  1205. borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
  1206. ),
  1207. builder: (sheetCtx) => SymbolPickerSheet(
  1208. currentSymbol: widget.symbol,
  1209. visibleTabs: const [SymbolPickerTab.futures],
  1210. onSelected: (newSymbol) {
  1211. Navigator.pop(sheetCtx);
  1212. context.go('$targetBasePath/$newSymbol');
  1213. },
  1214. onSpotSelected: (newSymbol) {
  1215. Navigator.pop(sheetCtx);
  1216. context.go('$targetBasePath/$newSymbol');
  1217. },
  1218. ),
  1219. );
  1220. }
  1221. void _showAmountUnitSheet(BuildContext context, FuturesNotifier notifier) {
  1222. FocusScope.of(context).unfocus();
  1223. final cs = Theme.of(context).colorScheme;
  1224. final coinLabel = ref.read(futuresProvider(widget.symbol).select((s) {
  1225. if (s.coinSymbol.isNotEmpty) return s.coinSymbol;
  1226. final base =
  1227. widget.symbol.toUpperCase().replaceFirst(RegExp(r'USDT$'), '');
  1228. return base.isNotEmpty ? base : 'BTC';
  1229. }));
  1230. final currentUnit =
  1231. ref.read(futuresProvider(widget.symbol).select((s) => s.amountUnit));
  1232. // 各单位的标题和描述
  1233. final l10n = AppLocalizations.of(context)!;
  1234. String unitTitle(AmountUnit unit) {
  1235. switch (unit) {
  1236. case AmountUnit.btc:
  1237. return l10n.contractUnitCoin(coinLabel);
  1238. case AmountUnit.usdt:
  1239. return l10n.contractUnitUsdt;
  1240. case AmountUnit.lots:
  1241. return l10n.contractUnitSheets;
  1242. }
  1243. }
  1244. String unitDesc(AmountUnit unit) {
  1245. switch (unit) {
  1246. case AmountUnit.btc:
  1247. return l10n.contractUnitHintCoin(coinLabel);
  1248. case AmountUnit.usdt:
  1249. return l10n.contractUnitHintUsdt;
  1250. case AmountUnit.lots:
  1251. return l10n.contractUnitHintSheets;
  1252. }
  1253. }
  1254. showModalBottomSheet<void>(
  1255. context: context,
  1256. useRootNavigator: true,
  1257. isScrollControlled: true,
  1258. backgroundColor: cs.surface,
  1259. shape: const RoundedRectangleBorder(
  1260. borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
  1261. ),
  1262. builder: (_) => StatefulBuilder(
  1263. builder: (ctx, setState) {
  1264. AmountUnit selected = currentUnit;
  1265. return SafeArea(
  1266. child: SingleChildScrollView(
  1267. padding: const EdgeInsets.fromLTRB(16, 20, 16, 16),
  1268. child: Column(
  1269. mainAxisSize: MainAxisSize.min,
  1270. crossAxisAlignment: CrossAxisAlignment.start,
  1271. children: [
  1272. Text(
  1273. l10n.contractUnitSetting,
  1274. style: TextStyle(
  1275. color: cs.onSurface,
  1276. fontSize: 16,
  1277. fontWeight: FontWeight.w600,
  1278. ),
  1279. ),
  1280. const SizedBox(height: 16),
  1281. for (final unit in AmountUnit.values) ...[
  1282. GestureDetector(
  1283. onTap: () {
  1284. notifier.setAmountUnit(unit);
  1285. // 单位切换后清空输入和滑块,避免旧值被误用
  1286. _amountController.clear();
  1287. notifier.setSliderPercent(0);
  1288. Navigator.pop(ctx);
  1289. },
  1290. child: Container(
  1291. width: double.infinity,
  1292. padding: const EdgeInsets.symmetric(
  1293. horizontal: 14, vertical: 14),
  1294. decoration: BoxDecoration(
  1295. border: Border.all(
  1296. color: selected == unit
  1297. ? cs.primary
  1298. : cs.outline.withAlpha(80),
  1299. width: selected == unit ? 1.5 : 1,
  1300. ),
  1301. borderRadius: BorderRadius.circular(8),
  1302. color: selected == unit
  1303. ? cs.primary.withAlpha(15)
  1304. : Colors.transparent,
  1305. ),
  1306. child: Column(
  1307. crossAxisAlignment: CrossAxisAlignment.start,
  1308. children: [
  1309. Text(
  1310. unitTitle(unit),
  1311. style: TextStyle(
  1312. color: cs.onSurface,
  1313. fontSize: 14,
  1314. fontWeight: FontWeight.w500,
  1315. ),
  1316. ),
  1317. const SizedBox(height: 4),
  1318. Text(
  1319. unitDesc(unit),
  1320. style: TextStyle(
  1321. color: cs.onSurface.withAlpha(140),
  1322. fontSize: 12,
  1323. ),
  1324. ),
  1325. ],
  1326. ),
  1327. ),
  1328. ),
  1329. if (unit != AmountUnit.lots) const SizedBox(height: 10),
  1330. ],
  1331. ],
  1332. ),
  1333. ),
  1334. );
  1335. },
  1336. ),
  1337. );
  1338. }
  1339. }
  1340. class _MarginLeverageRow extends ConsumerWidget {
  1341. const _MarginLeverageRow({required this.symbol});
  1342. final String symbol;
  1343. @override
  1344. Widget build(BuildContext context, WidgetRef ref) {
  1345. final cs = Theme.of(context).colorScheme;
  1346. final provider = futuresProvider(symbol);
  1347. final marginMode = ref.watch(provider.select((s) => s.marginMode));
  1348. final leverage = ref.watch(provider.select((s) => s.leverage));
  1349. final leverageMin = ref.watch(provider.select((s) => s.leverageMin));
  1350. final leverageMax = ref.watch(provider.select((s) => s.leverageMax));
  1351. final leverageOptions =
  1352. ref.watch(provider.select((s) => s.leverageOptions));
  1353. final isDiscrete = ref.watch(provider.select((s) => s.isDiscreteLeverage));
  1354. final notifier = ref.read(provider.notifier);
  1355. final isLoggedIn = ref.watch(isLoggedInProvider);
  1356. final isTrader = ref.watch(copyTradingProvider.select((s) => s.isTrader));
  1357. return Row(
  1358. children: [
  1359. Builder(builder: (ctx) {
  1360. final isDark = Theme.of(ctx).brightness == Brightness.dark;
  1361. return GestureDetector(
  1362. onTap: () => isLoggedIn
  1363. ? _showMarginModeSheet(context, marginMode, notifier,
  1364. isTrader: isTrader)
  1365. : context.push('/login'),
  1366. child: Container(
  1367. height: 26,
  1368. padding: const EdgeInsets.symmetric(horizontal: 7),
  1369. decoration: BoxDecoration(
  1370. color: isDark
  1371. ? AppColors.darkBgTertiary
  1372. : AppColors.lightBgTertiary,
  1373. borderRadius: BorderRadius.circular(4),
  1374. ),
  1375. child: Row(
  1376. mainAxisSize: MainAxisSize.min,
  1377. children: [
  1378. Text(
  1379. switch (marginMode) {
  1380. MarginMode.cross =>
  1381. AppLocalizations.of(context)!.crossMargin,
  1382. MarginMode.isolated =>
  1383. AppLocalizations.of(context)!.isolatedMargin,
  1384. MarginMode.split =>
  1385. AppLocalizations.of(context)!.splitMargin,
  1386. },
  1387. style: TextStyle(
  1388. color: cs.onSurface.withAlpha(153),
  1389. fontSize: 13,
  1390. fontWeight: FontWeight.w700)),
  1391. Icon(Icons.keyboard_arrow_down,
  1392. color: cs.onSurface.withAlpha(153), size: 13),
  1393. ],
  1394. ),
  1395. ),
  1396. );
  1397. }),
  1398. const SizedBox(width: 8),
  1399. GestureDetector(
  1400. onTap: () {
  1401. if (!isLoggedIn) {
  1402. context.push('/login');
  1403. return;
  1404. }
  1405. _showLeverageSheet(context, leverage, leverageMin, leverageMax,
  1406. leverageOptions, isDiscrete, notifier);
  1407. },
  1408. child: Container(
  1409. height: 26,
  1410. padding: const EdgeInsets.symmetric(horizontal: 7),
  1411. decoration: const BoxDecoration(
  1412. color: AppColors.leverageGoldBg,
  1413. borderRadius: BorderRadius.all(Radius.circular(4)),
  1414. ),
  1415. child: Row(
  1416. mainAxisSize: MainAxisSize.min,
  1417. children: [
  1418. Text(
  1419. '${leverage.toInt()}X',
  1420. style: const TextStyle(
  1421. color: AppColors.leverageGold,
  1422. fontSize: 13,
  1423. fontWeight: FontWeight.w700,
  1424. fontFeatures: [FontFeature.tabularFigures()],
  1425. ),
  1426. ),
  1427. const Icon(Icons.keyboard_arrow_down,
  1428. color: AppColors.leverageGold, size: 13),
  1429. ],
  1430. ),
  1431. ),
  1432. ),
  1433. ],
  1434. );
  1435. }
  1436. void _showLeverageSheet(
  1437. BuildContext context,
  1438. double leverage,
  1439. int leverageMin,
  1440. int leverageMax,
  1441. List<int> leverageOptions,
  1442. bool isDiscrete,
  1443. FuturesNotifier notifier) {
  1444. FocusScope.of(context).unfocus();
  1445. showModalBottomSheet<void>(
  1446. context: context,
  1447. useRootNavigator: true,
  1448. backgroundColor: Theme.of(context).colorScheme.surface,
  1449. shape: const RoundedRectangleBorder(
  1450. borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
  1451. ),
  1452. builder: (_) => _LeverageSheet(
  1453. symbol: symbol,
  1454. current: leverage,
  1455. leverageMin: leverageMin,
  1456. leverageMax: leverageMax,
  1457. leverageOptions: leverageOptions,
  1458. isDiscrete: isDiscrete,
  1459. onChanged: notifier.setLeverage,
  1460. ),
  1461. );
  1462. }
  1463. void _showMarginModeSheet(
  1464. BuildContext context, MarginMode current, FuturesNotifier notifier,
  1465. {bool isTrader = false}) {
  1466. FocusScope.of(context).unfocus();
  1467. final cs = Theme.of(context).colorScheme;
  1468. showModalBottomSheet<void>(
  1469. context: context,
  1470. useRootNavigator: true,
  1471. isScrollControlled: true,
  1472. backgroundColor: cs.surface,
  1473. shape: const RoundedRectangleBorder(
  1474. borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
  1475. ),
  1476. builder: (sheetCtx) => SafeArea(
  1477. child: SingleChildScrollView(
  1478. child: Column(
  1479. mainAxisSize: MainAxisSize.min,
  1480. crossAxisAlignment: CrossAxisAlignment.start,
  1481. children: [
  1482. Padding(
  1483. padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
  1484. child: Text(AppLocalizations.of(context)!.marginMode,
  1485. style: TextStyle(
  1486. color: cs.onSurface,
  1487. fontSize: 16,
  1488. fontWeight: FontWeight.w600)),
  1489. ),
  1490. Padding(
  1491. padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
  1492. child: Column(
  1493. children: [
  1494. for (final entry in [
  1495. (
  1496. MarginMode.cross,
  1497. AppLocalizations.of(context)!.crossMargin,
  1498. AppLocalizations.of(context)!.crossMarginDesc,
  1499. _MarginModeIcon.cross
  1500. ),
  1501. // 带单员不支持分仓,隐藏分仓选项
  1502. if (!isTrader)
  1503. (
  1504. MarginMode.split,
  1505. AppLocalizations.of(context)!.splitMargin,
  1506. AppLocalizations.of(context)!.splitMarginDesc,
  1507. _MarginModeIcon.split
  1508. ),
  1509. ]) ...[
  1510. GestureDetector(
  1511. onTap: () async {
  1512. Navigator.pop(sheetCtx);
  1513. final err = await notifier.setMarginMode(entry.$1);
  1514. if (err != null && context.mounted) {
  1515. showTopToast(context,
  1516. message: AppLocalizations.of(context)!
  1517. .switchMarginModeFailed);
  1518. }
  1519. },
  1520. child: Container(
  1521. width: double.infinity,
  1522. padding: const EdgeInsets.symmetric(
  1523. horizontal: 14, vertical: 12),
  1524. decoration: BoxDecoration(
  1525. border: Border.all(
  1526. color:
  1527. current == entry.$1 ? cs.onSurface : cs.outline,
  1528. width: current == entry.$1 ? 1.5 : 1,
  1529. ),
  1530. borderRadius: BorderRadius.circular(10),
  1531. color: Colors.transparent,
  1532. ),
  1533. child: Row(
  1534. crossAxisAlignment: CrossAxisAlignment.start,
  1535. children: [
  1536. _MarginModeIconWidget(type: entry.$4),
  1537. const SizedBox(width: 12),
  1538. Expanded(
  1539. child: Column(
  1540. crossAxisAlignment: CrossAxisAlignment.start,
  1541. children: [
  1542. Row(
  1543. children: [
  1544. Text(entry.$2,
  1545. style: TextStyle(
  1546. color: cs.onSurface,
  1547. fontWeight: FontWeight.w600,
  1548. fontSize: 14)),
  1549. if (current == entry.$1) ...[
  1550. const SizedBox(width: 6),
  1551. Icon(Icons.check_circle,
  1552. size: 16, color: cs.onSurface),
  1553. ],
  1554. ],
  1555. ),
  1556. const SizedBox(height: 4),
  1557. Text(entry.$3,
  1558. style: TextStyle(
  1559. color: cs.onSurface.withAlpha(120),
  1560. fontSize: 12,
  1561. height: 1.4)),
  1562. ],
  1563. ),
  1564. ),
  1565. ],
  1566. ),
  1567. ),
  1568. ),
  1569. const SizedBox(height: 10),
  1570. ],
  1571. ],
  1572. ),
  1573. ),
  1574. Padding(
  1575. padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
  1576. child: Center(
  1577. child: Text(
  1578. AppLocalizations.of(context)!.marginModeNote,
  1579. style: TextStyle(
  1580. color:
  1581. Theme.of(sheetCtx).colorScheme.onSurface.withAlpha(120),
  1582. fontSize: 11,
  1583. decoration: TextDecoration.underline,
  1584. decorationColor:
  1585. Theme.of(sheetCtx).colorScheme.onSurface.withAlpha(120),
  1586. ),
  1587. ),
  1588. ),
  1589. ),
  1590. ],
  1591. )),
  1592. ),
  1593. );
  1594. }
  1595. }
  1596. class _LeverageSheet extends StatefulWidget {
  1597. const _LeverageSheet({
  1598. required this.symbol,
  1599. required this.current,
  1600. required this.onChanged,
  1601. this.leverageMin = 1,
  1602. this.leverageMax = 125,
  1603. this.leverageOptions = const [],
  1604. this.isDiscrete = false,
  1605. });
  1606. final String symbol;
  1607. final double current;
  1608. final Future<String?> Function(double) onChanged;
  1609. final int leverageMin;
  1610. final int leverageMax;
  1611. final List<int> leverageOptions;
  1612. /// true=分离倍数(只能选指定档位)false=连续倍数(区间内任意值)
  1613. final bool isDiscrete;
  1614. @override
  1615. State<_LeverageSheet> createState() => _LeverageSheetState();
  1616. }
  1617. class _LeverageSheetState extends State<_LeverageSheet> {
  1618. late double _value;
  1619. bool _loading = false;
  1620. /// 预设档位:优先用接口返回的 leverageOptions,否则用默认
  1621. List<int> get _presets {
  1622. if (widget.leverageOptions.isNotEmpty) return widget.leverageOptions;
  1623. return [1, 5, 10, 30, 50, 75, 100, 125]
  1624. .where((v) => v >= widget.leverageMin && v <= widget.leverageMax)
  1625. .toList();
  1626. }
  1627. @override
  1628. void initState() {
  1629. super.initState();
  1630. final clamped = widget.current
  1631. .clamp(widget.leverageMin.toDouble(), widget.leverageMax.toDouble());
  1632. if (widget.isDiscrete && widget.leverageOptions.isNotEmpty) {
  1633. // 离散模式:对齐到最近档位
  1634. final cur = clamped.toInt();
  1635. final nearest = widget.leverageOptions.reduce(
  1636. (a, b) => (a - cur).abs() <= (b - cur).abs() ? a : b,
  1637. );
  1638. _value = nearest.toDouble();
  1639. } else {
  1640. _value = clamped;
  1641. }
  1642. }
  1643. void _step(int delta) {
  1644. if (widget.isDiscrete && _presets.isNotEmpty) {
  1645. // 离散模式:跳到相邻档位
  1646. final cur = _value.toInt();
  1647. final idx = _presets.indexOf(cur);
  1648. int nextIdx;
  1649. if (idx < 0) {
  1650. // 当前值不在档位中,找最近的
  1651. nextIdx = delta > 0
  1652. ? _presets.indexWhere((v) => v > cur)
  1653. : _presets.lastIndexWhere((v) => v < cur);
  1654. } else {
  1655. nextIdx = idx + delta.sign;
  1656. }
  1657. if (nextIdx >= 0 && nextIdx < _presets.length) {
  1658. setState(() => _value = _presets[nextIdx].toDouble());
  1659. }
  1660. } else {
  1661. final next = (_value + delta)
  1662. .clamp(widget.leverageMin.toDouble(), widget.leverageMax.toDouble());
  1663. setState(() => _value = next);
  1664. }
  1665. }
  1666. @override
  1667. Widget build(BuildContext context) {
  1668. final cs = Theme.of(context).colorScheme;
  1669. final isDark = Theme.of(context).brightness == Brightness.dark;
  1670. return SafeArea(
  1671. child: Padding(
  1672. padding: const EdgeInsets.fromLTRB(20, 0, 20, 24),
  1673. child: Column(
  1674. mainAxisSize: MainAxisSize.min,
  1675. children: [
  1676. // ── 顶部标题栏 ──────────────────────────────────
  1677. Padding(
  1678. padding: const EdgeInsets.symmetric(vertical: 16),
  1679. child: Row(
  1680. children: [
  1681. const SizedBox(width: 32),
  1682. Expanded(
  1683. child: Column(
  1684. children: [
  1685. Text(
  1686. AppLocalizations.of(context)!
  1687. .symbolPerpetual(widget.symbol),
  1688. style: TextStyle(
  1689. color: cs.onSurface,
  1690. fontSize: 16,
  1691. fontWeight: FontWeight.w700,
  1692. ),
  1693. textAlign: TextAlign.center,
  1694. ),
  1695. const SizedBox(height: 2),
  1696. Text(
  1697. AppLocalizations.of(context)!.adjustLeverage,
  1698. style: TextStyle(
  1699. color: cs.onSurface.withAlpha(120),
  1700. fontSize: 12,
  1701. ),
  1702. textAlign: TextAlign.center,
  1703. ),
  1704. ],
  1705. ),
  1706. ),
  1707. SizedBox(
  1708. width: 32,
  1709. child: GestureDetector(
  1710. onTap: () => Navigator.pop(context),
  1711. child: Icon(Icons.close,
  1712. size: 20, color: cs.onSurface.withAlpha(153)),
  1713. ),
  1714. ),
  1715. ],
  1716. ),
  1717. ),
  1718. // ── - | 倍数 | + ────────────────────────────────
  1719. Container(
  1720. height: 60,
  1721. decoration: BoxDecoration(
  1722. color: isDark ? AppColors.darkBgTertiary : Colors.white,
  1723. borderRadius: BorderRadius.circular(12),
  1724. border: Border.all(color: cs.outline.withAlpha(80)),
  1725. ),
  1726. child: Row(
  1727. children: [
  1728. _LeverageStepBtn(
  1729. label: '−',
  1730. onTap: () => _step(-1),
  1731. onLongPress: () => _step(-5),
  1732. isLeft: true,
  1733. ),
  1734. Container(
  1735. width: 1,
  1736. color:
  1737. Theme.of(context).colorScheme.outline.withAlpha(80)),
  1738. Expanded(
  1739. child: Center(
  1740. child: Text(
  1741. '${_value.toInt()}x',
  1742. style: TextStyle(
  1743. color: cs.onSurface,
  1744. fontSize: 26,
  1745. fontWeight: FontWeight.w700,
  1746. ),
  1747. ),
  1748. ),
  1749. ),
  1750. Container(
  1751. width: 1,
  1752. color:
  1753. Theme.of(context).colorScheme.outline.withAlpha(80)),
  1754. // + 按钮
  1755. _LeverageStepBtn(
  1756. label: '+',
  1757. onTap: () => _step(1),
  1758. onLongPress: () => _step(5),
  1759. isLeft: false,
  1760. ),
  1761. ],
  1762. ),
  1763. ),
  1764. const SizedBox(height: 20),
  1765. // ── 滑轨(连续模式显示,离散模式隐藏)────────────
  1766. if (!widget.isDiscrete) ...[
  1767. SliderTheme(
  1768. data: SliderTheme.of(context).copyWith(
  1769. activeTrackColor: AppColors.brand,
  1770. inactiveTrackColor: cs.outline.withAlpha(50),
  1771. thumbColor: Colors.white,
  1772. thumbShape:
  1773. const RoundSliderThumbShape(enabledThumbRadius: 10),
  1774. overlayShape:
  1775. const RoundSliderOverlayShape(overlayRadius: 18),
  1776. overlayColor: cs.onSurface.withAlpha(20),
  1777. trackHeight: 3,
  1778. ),
  1779. child: Slider(
  1780. value: _value,
  1781. min: widget.leverageMin.toDouble(),
  1782. max: widget.leverageMax.toDouble(),
  1783. divisions:
  1784. (widget.leverageMax - widget.leverageMin).clamp(1, 999),
  1785. onChanged: (v) => setState(() => _value = v.roundToDouble()),
  1786. ),
  1787. ),
  1788. const SizedBox(height: 12),
  1789. ],
  1790. // ── 档位按钮(两种模式都显示,离散时为唯一选择方式)
  1791. Wrap(
  1792. spacing: 8,
  1793. runSpacing: 8,
  1794. children: _presets.map((v) {
  1795. final active = _value.toInt() == v;
  1796. return GestureDetector(
  1797. onTap: () => setState(() => _value = v.toDouble()),
  1798. child: Container(
  1799. padding:
  1800. const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
  1801. decoration: BoxDecoration(
  1802. color:
  1803. active ? AppColors.brand : cs.outline.withAlpha(25),
  1804. borderRadius: BorderRadius.circular(8),
  1805. ),
  1806. child: Text(
  1807. '${v}x',
  1808. style: TextStyle(
  1809. color:
  1810. active ? Colors.black : cs.onSurface.withAlpha(153),
  1811. fontSize: 12,
  1812. fontWeight: FontWeight.w500,
  1813. ),
  1814. ),
  1815. ),
  1816. );
  1817. }).toList(),
  1818. ),
  1819. const SizedBox(height: 24),
  1820. // ── 确定按钮 ─────────────────────────────────────
  1821. SizedBox(
  1822. width: double.infinity,
  1823. height: 52,
  1824. child: ElevatedButton(
  1825. onPressed: _loading
  1826. ? null
  1827. : () async {
  1828. setState(() => _loading = true);
  1829. final err = await widget.onChanged(_value);
  1830. if (!context.mounted) return;
  1831. setState(() => _loading = false);
  1832. showTopToast(
  1833. context,
  1834. message: err ??
  1835. AppLocalizations.of(context)!
  1836. .leverageAdjustedMsg(_value.toInt()),
  1837. backgroundColor:
  1838. err != null ? AppColors.fall : AppColors.rise,
  1839. );
  1840. if (err == null) Navigator.pop(context);
  1841. },
  1842. style: ElevatedButton.styleFrom(
  1843. backgroundColor: AppColors.brand,
  1844. elevation: 0,
  1845. shape: RoundedRectangleBorder(
  1846. borderRadius: BorderRadius.circular(26)),
  1847. ),
  1848. child: _loading
  1849. ? SizedBox(
  1850. width: 20,
  1851. height: 20,
  1852. child: CircularProgressIndicator(
  1853. strokeWidth: 2, color: Colors.black),
  1854. )
  1855. : Text(AppLocalizations.of(context)!.confirmLabel,
  1856. style: TextStyle(
  1857. color: Colors.black,
  1858. fontSize: 16,
  1859. fontWeight: FontWeight.w600)),
  1860. ),
  1861. ),
  1862. ],
  1863. ),
  1864. ),
  1865. );
  1866. }
  1867. }
  1868. /// 杠杆调节 -/+ 按钮
  1869. class _LeverageStepBtn extends StatelessWidget {
  1870. const _LeverageStepBtn({
  1871. required this.label,
  1872. required this.onTap,
  1873. required this.onLongPress,
  1874. this.isLeft = true,
  1875. });
  1876. final String label;
  1877. final VoidCallback onTap;
  1878. final VoidCallback onLongPress;
  1879. final bool isLeft;
  1880. @override
  1881. Widget build(BuildContext context) {
  1882. final cs = Theme.of(context).colorScheme;
  1883. final radius = Radius.circular(11);
  1884. return GestureDetector(
  1885. onTap: onTap,
  1886. onLongPress: onLongPress,
  1887. child: Container(
  1888. width: 60,
  1889. alignment: Alignment.center,
  1890. decoration: BoxDecoration(
  1891. color: cs.outline.withAlpha(25),
  1892. borderRadius: isLeft
  1893. ? BorderRadius.only(topLeft: radius, bottomLeft: radius)
  1894. : BorderRadius.only(topRight: radius, bottomRight: radius),
  1895. ),
  1896. child: Text(
  1897. label,
  1898. style: TextStyle(
  1899. color: cs.onSurface,
  1900. fontSize: 24,
  1901. fontWeight: FontWeight.w400,
  1902. ),
  1903. ),
  1904. ),
  1905. );
  1906. }
  1907. }
  1908. class _PositionModePills extends ConsumerWidget {
  1909. const _PositionModePills({required this.symbol});
  1910. final String symbol;
  1911. @override
  1912. Widget build(BuildContext context, WidgetRef ref) {
  1913. final cs = Theme.of(context).colorScheme;
  1914. final provider = futuresProvider(symbol);
  1915. final positionMode = ref.watch(provider.select((s) => s.positionMode));
  1916. final notifier = ref.read(provider.notifier);
  1917. final isOpen = positionMode == PositionMode.open;
  1918. return Container(
  1919. height: 30,
  1920. padding: const EdgeInsets.all(2),
  1921. decoration: BoxDecoration(
  1922. color: cs.outline.withAlpha(80),
  1923. borderRadius: BorderRadius.circular(999),
  1924. ),
  1925. child: Row(
  1926. children: [
  1927. _SegPill(
  1928. label: AppLocalizations.of(context)!.openLabel,
  1929. active: isOpen,
  1930. activeColor: AppColors.rise,
  1931. onTap: () => notifier.setPositionMode(PositionMode.open),
  1932. ),
  1933. _SegPill(
  1934. label: AppLocalizations.of(context)!.closeLabel,
  1935. active: !isOpen,
  1936. activeColor: AppColors.fall,
  1937. onTap: () => notifier.setPositionMode(PositionMode.close),
  1938. ),
  1939. ],
  1940. ),
  1941. );
  1942. }
  1943. }
  1944. class _SegPill extends StatelessWidget {
  1945. const _SegPill({
  1946. required this.label,
  1947. required this.active,
  1948. required this.activeColor,
  1949. required this.onTap,
  1950. });
  1951. final String label;
  1952. final bool active;
  1953. final Color activeColor;
  1954. final VoidCallback onTap;
  1955. @override
  1956. Widget build(BuildContext context) {
  1957. final cs = Theme.of(context).colorScheme;
  1958. return Expanded(
  1959. child: GestureDetector(
  1960. onTap: onTap,
  1961. child: AnimatedContainer(
  1962. duration: const Duration(milliseconds: 150),
  1963. decoration: BoxDecoration(
  1964. color: active ? activeColor : Colors.transparent,
  1965. borderRadius: BorderRadius.circular(999),
  1966. ),
  1967. alignment: Alignment.center,
  1968. child: Text(
  1969. label,
  1970. style: TextStyle(
  1971. color: active ? Colors.white : cs.onSurface.withAlpha(153),
  1972. fontSize: 12,
  1973. fontWeight: FontWeight.w600,
  1974. ),
  1975. ),
  1976. ),
  1977. ),
  1978. );
  1979. }
  1980. }
  1981. class _OrderTypeDropdown extends ConsumerWidget {
  1982. const _OrderTypeDropdown({required this.symbol});
  1983. final String symbol;
  1984. @override
  1985. Widget build(BuildContext context, WidgetRef ref) {
  1986. final cs = Theme.of(context).colorScheme;
  1987. final provider = futuresProvider(symbol);
  1988. final orderType = ref.watch(provider.select((s) => s.orderType));
  1989. final isClose =
  1990. ref.watch(provider.select((s) => s.positionMode == PositionMode.close));
  1991. final notifier = ref.read(provider.notifier);
  1992. final isDark = Theme.of(context).brightness == Brightness.dark;
  1993. return GestureDetector(
  1994. onTap: () => _showOrderTypeMenu(context, orderType, isClose, notifier),
  1995. child: Container(
  1996. height: 36,
  1997. padding: const EdgeInsets.symmetric(horizontal: 10),
  1998. decoration: BoxDecoration(
  1999. color:
  2000. isDark ? AppColors.darkBgSecondary : AppColors.lightBgSecondary,
  2001. borderRadius: BorderRadius.circular(8),
  2002. ),
  2003. child: Row(
  2004. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  2005. children: [
  2006. Text(
  2007. () {
  2008. final l10n = AppLocalizations.of(context)!;
  2009. switch (orderType) {
  2010. case OrderType.market:
  2011. return l10n.marketOrder;
  2012. case OrderType.limit:
  2013. return l10n.limitOrder;
  2014. case OrderType.conditionalMarket:
  2015. return l10n.conditionalMarketOrder;
  2016. case OrderType.conditionalLimit:
  2017. return l10n.conditionalLimitOrder;
  2018. }
  2019. }(),
  2020. style: TextStyle(color: cs.onSurface, fontSize: 13),
  2021. ),
  2022. Icon(Icons.keyboard_arrow_down,
  2023. color: cs.onSurface.withAlpha(153), size: 18),
  2024. ],
  2025. ),
  2026. ),
  2027. );
  2028. }
  2029. void _showOrderTypeMenu(BuildContext context, OrderType currentType,
  2030. bool isClose, FuturesNotifier notifier) {
  2031. FocusScope.of(context).unfocus();
  2032. final cs = Theme.of(context).colorScheme;
  2033. final l10n = AppLocalizations.of(context)!;
  2034. final types = [
  2035. (OrderType.market, l10n.marketOrder),
  2036. (OrderType.limit, l10n.limitOrder),
  2037. if (!isClose) (OrderType.conditionalMarket, l10n.conditionalMarketOrder),
  2038. if (!isClose) (OrderType.conditionalLimit, l10n.conditionalLimitOrder),
  2039. ];
  2040. showModalBottomSheet<void>(
  2041. context: context,
  2042. useRootNavigator: true,
  2043. backgroundColor: cs.surface,
  2044. shape: const RoundedRectangleBorder(
  2045. borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
  2046. ),
  2047. builder: (sheetCtx) => SafeArea(
  2048. child: Column(
  2049. mainAxisSize: MainAxisSize.min,
  2050. children: types
  2051. .map((t) => GestureDetector(
  2052. onTap: () {
  2053. notifier.setOrderType(t.$1);
  2054. Navigator.pop(sheetCtx);
  2055. },
  2056. child: Padding(
  2057. padding: const EdgeInsets.symmetric(
  2058. horizontal: 16, vertical: 14),
  2059. child: Row(
  2060. children: [
  2061. Expanded(
  2062. child: Text(t.$2,
  2063. style: TextStyle(
  2064. color: currentType == t.$1
  2065. ? AppColors.brand
  2066. : cs.onSurface,
  2067. fontSize: 14)),
  2068. ),
  2069. if (currentType == t.$1)
  2070. const Icon(Icons.check,
  2071. color: AppColors.brand, size: 18),
  2072. ],
  2073. ),
  2074. ),
  2075. ))
  2076. .toList(),
  2077. ),
  2078. ),
  2079. );
  2080. }
  2081. }
  2082. // ── 保证金模式图标 ─────────────────────────────────────────────
  2083. enum _MarginModeIcon { cross, split }
  2084. class _MarginModeIconWidget extends StatelessWidget {
  2085. const _MarginModeIconWidget({required this.type});
  2086. final _MarginModeIcon type;
  2087. @override
  2088. Widget build(BuildContext context) {
  2089. final asset = switch (type) {
  2090. _MarginModeIcon.cross => 'assets/images/eg_ticket_dark.png',
  2091. _MarginModeIcon.split => 'assets/images/eg_split.png',
  2092. };
  2093. return Image.asset(asset, width: 52, height: 52, fit: BoxFit.contain);
  2094. }
  2095. }
  2096. class _LargeInput extends StatefulWidget {
  2097. const _LargeInput({
  2098. super.key,
  2099. required this.controller,
  2100. required this.label,
  2101. required this.unit,
  2102. this.suffixDropdown,
  2103. this.showUnitDropdown = false,
  2104. this.onUnitTap,
  2105. this.inputFormatters,
  2106. });
  2107. final TextEditingController controller;
  2108. final String label;
  2109. final String unit;
  2110. final String? suffixDropdown;
  2111. final bool showUnitDropdown;
  2112. final VoidCallback? onUnitTap;
  2113. final List<TextInputFormatter>? inputFormatters;
  2114. @override
  2115. State<_LargeInput> createState() => _LargeInputState();
  2116. }
  2117. class _LargeInputState extends State<_LargeInput>
  2118. with SingleTickerProviderStateMixin {
  2119. final _focusNode = FocusNode();
  2120. late final AnimationController _animCtrl;
  2121. late final Animation<double> _curvedAnim;
  2122. // 是否处于激活态(聚焦 或 有内容)
  2123. bool get _isActive =>
  2124. _focusNode.hasFocus || widget.controller.text.isNotEmpty;
  2125. @override
  2126. void initState() {
  2127. super.initState();
  2128. _animCtrl = AnimationController(
  2129. vsync: this,
  2130. duration: const Duration(milliseconds: 220),
  2131. );
  2132. _curvedAnim = CurvedAnimation(
  2133. parent: _animCtrl,
  2134. curve: const Cubic(0.4, 0.0, 0.2, 1.0), // 与原型一致
  2135. );
  2136. _focusNode.addListener(_onChanged);
  2137. widget.controller.addListener(_onChanged);
  2138. // 若初始时已有内容,跳过动画直接到激活态
  2139. if (_isActive) _animCtrl.value = 1.0;
  2140. }
  2141. @override
  2142. void didUpdateWidget(_LargeInput oldWidget) {
  2143. super.didUpdateWidget(oldWidget);
  2144. if (oldWidget.controller != widget.controller) {
  2145. // controller 实例变化时:移除旧监听、绑定新监听,并同步动画状态
  2146. oldWidget.controller.removeListener(_onChanged);
  2147. widget.controller.addListener(_onChanged);
  2148. if (_isActive) {
  2149. _animCtrl.value = 1.0;
  2150. } else {
  2151. _animCtrl.value = 0.0;
  2152. }
  2153. }
  2154. }
  2155. void _onChanged() {
  2156. if (_isActive) {
  2157. _animCtrl.forward();
  2158. } else {
  2159. _animCtrl.reverse();
  2160. }
  2161. setState(() {});
  2162. }
  2163. @override
  2164. void dispose() {
  2165. _focusNode.removeListener(_onChanged);
  2166. widget.controller.removeListener(_onChanged);
  2167. _focusNode.dispose();
  2168. _animCtrl.dispose();
  2169. super.dispose();
  2170. }
  2171. @override
  2172. Widget build(BuildContext context) {
  2173. final cs = Theme.of(context).colorScheme;
  2174. final isDark = Theme.of(context).brightness == Brightness.dark;
  2175. final unfocusedBg =
  2176. isDark ? AppColors.darkBgTertiary : AppColors.lightBgSecondary;
  2177. final focusedBg = isDark ? AppColors.darkBgSecondary : Colors.white;
  2178. final activeBorderColor = isDark
  2179. ? AppColors.darkTextPrimary.withAlpha(200)
  2180. : const Color(0xFF383838);
  2181. return GestureDetector(
  2182. behavior: HitTestBehavior.opaque,
  2183. onTap: () => _focusNode.requestFocus(),
  2184. child: Container(
  2185. height: 44,
  2186. padding: const EdgeInsets.symmetric(horizontal: 12),
  2187. decoration: BoxDecoration(
  2188. color: _focusNode.hasFocus ? focusedBg : unfocusedBg,
  2189. borderRadius: BorderRadius.circular(8),
  2190. border: _focusNode.hasFocus
  2191. ? Border.all(color: activeBorderColor, width: 1.5)
  2192. : null,
  2193. ),
  2194. child: Row(
  2195. crossAxisAlignment: CrossAxisAlignment.center,
  2196. children: [
  2197. Expanded(
  2198. child: AnimatedBuilder(
  2199. animation: _curvedAnim,
  2200. builder: (context, inputChild) {
  2201. final t = _curvedAnim.value;
  2202. final labelSize = 13.0 + (10.0 - 13.0) * t;
  2203. final labelColor = isDark
  2204. ? AppColors.darkTextSecondary
  2205. : AppColors.lightTextSecondary;
  2206. final labelHeight = labelSize * 1.0;
  2207. final centerTop = (44.0 - labelHeight) / 2;
  2208. const activeTop = 5.0;
  2209. final labelTop = centerTop + (activeTop - centerTop) * t;
  2210. final inputOpacity = t;
  2211. return SizedBox(
  2212. height: 44,
  2213. child: Stack(
  2214. clipBehavior: Clip.none,
  2215. children: [
  2216. Positioned(
  2217. top: labelTop,
  2218. left: 0,
  2219. right: 0,
  2220. child: Text(
  2221. widget.label,
  2222. style: TextStyle(
  2223. color: labelColor,
  2224. fontSize: labelSize,
  2225. height: 1.0,
  2226. ),
  2227. ),
  2228. ),
  2229. Positioned(
  2230. bottom: 5,
  2231. left: 0,
  2232. right: 0,
  2233. child: Opacity(
  2234. opacity: inputOpacity,
  2235. child: inputChild,
  2236. ),
  2237. ),
  2238. ],
  2239. ),
  2240. );
  2241. },
  2242. child: TextField(
  2243. focusNode: _focusNode,
  2244. controller: widget.controller,
  2245. keyboardType:
  2246. const TextInputType.numberWithOptions(decimal: true),
  2247. inputFormatters: widget.inputFormatters,
  2248. style: TextStyle(
  2249. color: cs.onSurface,
  2250. fontSize: 14,
  2251. fontWeight: FontWeight.w500,
  2252. ),
  2253. decoration: const InputDecoration(
  2254. border: InputBorder.none,
  2255. focusedBorder: InputBorder.none,
  2256. enabledBorder: InputBorder.none,
  2257. filled: false,
  2258. isDense: true,
  2259. contentPadding: EdgeInsets.zero,
  2260. ),
  2261. ),
  2262. ),
  2263. ),
  2264. const SizedBox(width: 6),
  2265. GestureDetector(
  2266. behavior: HitTestBehavior.opaque,
  2267. onTap: widget.showUnitDropdown
  2268. ? () {
  2269. _focusNode.unfocus();
  2270. widget.onUnitTap?.call();
  2271. }
  2272. : null,
  2273. child: Row(
  2274. mainAxisSize: MainAxisSize.min,
  2275. children: [
  2276. Text(widget.unit,
  2277. style: TextStyle(
  2278. color: cs.onSurface.withAlpha(153), fontSize: 13)),
  2279. if (widget.showUnitDropdown)
  2280. Icon(Icons.keyboard_arrow_down,
  2281. color: cs.onSurface.withAlpha(153), size: 14),
  2282. ],
  2283. ),
  2284. ),
  2285. if (widget.suffixDropdown != null) ...[
  2286. const SizedBox(width: 6),
  2287. Row(
  2288. mainAxisSize: MainAxisSize.min,
  2289. children: [
  2290. Text(widget.suffixDropdown!,
  2291. style: TextStyle(
  2292. color: cs.onSurface.withAlpha(153), fontSize: 12)),
  2293. Icon(Icons.keyboard_arrow_down,
  2294. color: cs.onSurface.withAlpha(153), size: 14),
  2295. ],
  2296. ),
  2297. ],
  2298. ],
  2299. ),
  2300. ),
  2301. );
  2302. }
  2303. }
  2304. class _PercentSlider extends StatefulWidget {
  2305. const _PercentSlider({
  2306. required this.percent,
  2307. required this.onChanged,
  2308. this.showQuickButtons = true,
  2309. this.enabled = true,
  2310. });
  2311. final double percent;
  2312. final ValueChanged<double> onChanged;
  2313. final bool showQuickButtons;
  2314. /// false 时忽略所有手势,仅展示当前进度
  2315. final bool enabled;
  2316. @override
  2317. State<_PercentSlider> createState() => _PercentSliderState();
  2318. }
  2319. class _PercentSliderState extends State<_PercentSlider> {
  2320. // 行业标准快捷百分比(25/50/75/100,与主流交易所一致)
  2321. static const _quickPcts = [0.0, 0.25, 0.50, 0.75, 1.00];
  2322. static const _tickPcts = [0.0, 0.25, 0.50, 0.75, 1.00];
  2323. static const _thumbSize = 18.0;
  2324. static const _trackH = _thumbSize;
  2325. bool _isDragging = false;
  2326. double _lastHapticPct = -1;
  2327. // OverlayPortal:气泡渲染到 Overlay 层,不受任何祖先裁剪影响
  2328. final _overlayCtrl = OverlayPortalController();
  2329. // CompositedTransformTarget key,用于获取滑块在屏幕中的绝对位置
  2330. final _layerLink = LayerLink();
  2331. double _trackWidth = 0;
  2332. void _onDrag(double dx, double w) {
  2333. // 有效轨道范围:两端各留半个滑块
  2334. const r = _thumbSize / 2;
  2335. final trackW = w - _thumbSize;
  2336. final newPct = ((dx - r) / trackW).clamp(0.0, 1.0);
  2337. final lastStep = (_lastHapticPct * 100).floor();
  2338. final newStep = (newPct * 100).floor();
  2339. if (newStep != lastStep) HapticFeedback.selectionClick();
  2340. _lastHapticPct = newPct;
  2341. widget.onChanged(newPct);
  2342. }
  2343. void _startDrag(double dx, double w) {
  2344. _trackWidth = w;
  2345. setState(() => _isDragging = true);
  2346. _overlayCtrl.show();
  2347. _onDrag(dx, w);
  2348. }
  2349. void _endDrag() {
  2350. setState(() => _isDragging = false);
  2351. _overlayCtrl.hide();
  2352. }
  2353. @override
  2354. Widget build(BuildContext context) {
  2355. final cs = Theme.of(context).colorScheme;
  2356. final percent = widget.percent;
  2357. return Column(
  2358. crossAxisAlignment: CrossAxisAlignment.stretch,
  2359. children: [
  2360. // ── 滑轨区 ───────────────────────────────────────────
  2361. SizedBox(
  2362. height: _trackH,
  2363. child: LayoutBuilder(
  2364. builder: (_, box) {
  2365. final w = box.maxWidth;
  2366. // 轨道有效宽度:两端各留半个滑块,使 0%/100% 时滑块完整显示
  2367. const r = _thumbSize / 2;
  2368. final trackW = w - _thumbSize;
  2369. final thumbX = r + trackW * percent;
  2370. return CompositedTransformTarget(
  2371. link: _layerLink,
  2372. child: GestureDetector(
  2373. behavior: HitTestBehavior.opaque,
  2374. onHorizontalDragStart: widget.enabled
  2375. ? (d) => _startDrag(d.localPosition.dx, w)
  2376. : null,
  2377. onHorizontalDragUpdate: widget.enabled
  2378. ? (d) => _onDrag(d.localPosition.dx, w)
  2379. : null,
  2380. onHorizontalDragEnd:
  2381. widget.enabled ? (_) => _endDrag() : null,
  2382. onTapDown: widget.enabled
  2383. ? (d) {
  2384. // 触点转换为有效轨道范围内的百分比
  2385. final pct = ((d.localPosition.dx - r) / trackW)
  2386. .clamp(0.0, 1.0);
  2387. HapticFeedback.selectionClick();
  2388. _lastHapticPct = pct;
  2389. widget.onChanged(pct);
  2390. }
  2391. : null,
  2392. // OverlayPortal:气泡挂载到 Overlay,脱离布局树
  2393. child: OverlayPortal(
  2394. controller: _overlayCtrl,
  2395. overlayChildBuilder: (_) {
  2396. final tw = _trackWidth > 0 ? _trackWidth : w;
  2397. // 滑块圆心的 X:与 thumbX 计算方式一致
  2398. const bubbleR = _thumbSize / 2;
  2399. final effW = tw - _thumbSize;
  2400. final thumbCx = bubbleR + effW * percent;
  2401. // 气泡宽40,对齐滑块中心,边界夹紧
  2402. final bubbleOffsetX =
  2403. (thumbCx - 20).clamp(0.0, tw - 40.0);
  2404. // 气泡高30(24容器+6箭头),置于滑块上方 4px
  2405. const bubbleH = 30.0;
  2406. return Positioned(
  2407. left: 0,
  2408. top: 0,
  2409. child: CompositedTransformFollower(
  2410. link: _layerLink,
  2411. showWhenUnlinked: false,
  2412. // 从 target 左上角偏移:x=气泡位置,y=轨道上方
  2413. offset: Offset(bubbleOffsetX, -(bubbleH + 4)),
  2414. child: _PercentBubble(percent: percent),
  2415. ),
  2416. );
  2417. },
  2418. child: Stack(
  2419. children: [
  2420. // 背景轨道(两端与有效轨道对齐,即 r ~ w-r)
  2421. Positioned(
  2422. top: (_trackH - 3) / 2,
  2423. left: r,
  2424. right: r,
  2425. height: 3,
  2426. child: Container(
  2427. decoration: BoxDecoration(
  2428. color: cs.outline.withAlpha(50),
  2429. borderRadius: BorderRadius.circular(2),
  2430. ),
  2431. ),
  2432. ),
  2433. // 已填充轨道(从 r 开始到滑块圆心)
  2434. Positioned(
  2435. top: (_trackH - 3) / 2,
  2436. left: r,
  2437. width: thumbX - r,
  2438. height: 3,
  2439. child: Container(
  2440. decoration: BoxDecoration(
  2441. color: AppColors.brand,
  2442. borderRadius: BorderRadius.circular(2),
  2443. ),
  2444. ),
  2445. ),
  2446. // 刻度点(在有效轨道范围内按百分比定位)
  2447. for (final p in _tickPcts)
  2448. Positioned(
  2449. left: r + trackW * p - 3,
  2450. top: (_trackH - 6) / 2,
  2451. child: Container(
  2452. width: 6,
  2453. height: 6,
  2454. decoration: BoxDecoration(
  2455. shape: BoxShape.circle,
  2456. color: p <= percent
  2457. ? AppColors.brand
  2458. : cs.outline.withAlpha(80),
  2459. ),
  2460. ),
  2461. ),
  2462. // 滑块把手(圆心在 thumbX)
  2463. Positioned(
  2464. left: thumbX - r,
  2465. top: 0,
  2466. width: _thumbSize,
  2467. height: _thumbSize,
  2468. child: Container(
  2469. decoration: BoxDecoration(
  2470. color: Colors.white,
  2471. shape: BoxShape.circle,
  2472. border: Border.all(
  2473. color: AppColors.brand, width: 2.5),
  2474. boxShadow: [
  2475. BoxShadow(
  2476. color: Colors.black.withAlpha(70),
  2477. blurRadius: 5,
  2478. spreadRadius: 1,
  2479. offset: const Offset(0, 1.5),
  2480. ),
  2481. ],
  2482. ),
  2483. ),
  2484. ),
  2485. ],
  2486. ),
  2487. ),
  2488. ),
  2489. );
  2490. },
  2491. ),
  2492. ),
  2493. if (widget.showQuickButtons) ...[
  2494. const SizedBox(height: 4),
  2495. // ── 快捷按钮 0/25/50/75/100:Stack+Positioned,按钮中心与刻度对齐 ──
  2496. LayoutBuilder(builder: (_, box) {
  2497. final w = box.maxWidth;
  2498. const r = _thumbSize / 2;
  2499. final trackW = w - _thumbSize;
  2500. // 相邻刻度间距,减去固定间隙 6px,保证各机型按钮间隔一致
  2501. final tickInterval = trackW / (_quickPcts.length - 1);
  2502. final btnW = (tickInterval - 6).clamp(20.0, 64.0);
  2503. return SizedBox(
  2504. height: 22,
  2505. child: Stack(
  2506. children: [
  2507. for (final pct in _quickPcts)
  2508. Positioned(
  2509. // 按钮中心对齐刻度圆心,边界夹紧防止溢出
  2510. left: (r + trackW * pct - btnW / 2).clamp(0.0, w - btnW),
  2511. top: 0,
  2512. width: btnW,
  2513. height: 22,
  2514. child: Builder(builder: (_) {
  2515. final isSelected = (percent - pct).abs() < 0.001;
  2516. return GestureDetector(
  2517. onTap: widget.enabled
  2518. ? () {
  2519. HapticFeedback.selectionClick();
  2520. _lastHapticPct = pct;
  2521. widget.onChanged(pct);
  2522. }
  2523. : null,
  2524. child: Container(
  2525. decoration: BoxDecoration(
  2526. color: isSelected
  2527. ? AppColors.brand
  2528. : cs.outline.withAlpha(25),
  2529. borderRadius: BorderRadius.circular(4),
  2530. ),
  2531. alignment: Alignment.center,
  2532. child: Text(
  2533. '${(pct * 100).toInt()}%',
  2534. style: TextStyle(
  2535. color: isSelected
  2536. ? Colors.black
  2537. : cs.onSurface.withAlpha(102),
  2538. fontSize: 10,
  2539. fontWeight: FontWeight.w500,
  2540. ),
  2541. ),
  2542. ),
  2543. );
  2544. }),
  2545. ),
  2546. ],
  2547. ),
  2548. );
  2549. }),
  2550. ],
  2551. ],
  2552. );
  2553. }
  2554. }
  2555. /// 拖动时显示在滑块上方的百分比气泡(气泡 + 向下三角箭头)
  2556. class _PercentBubble extends StatelessWidget {
  2557. const _PercentBubble({required this.percent});
  2558. final double percent;
  2559. @override
  2560. Widget build(BuildContext context) {
  2561. final label = '${(percent * 100).round()}%';
  2562. return Column(
  2563. mainAxisSize: MainAxisSize.min,
  2564. children: [
  2565. Container(
  2566. width: 40,
  2567. height: 24,
  2568. alignment: Alignment.center,
  2569. decoration: BoxDecoration(
  2570. color: AppColors.brand,
  2571. borderRadius: BorderRadius.circular(6),
  2572. ),
  2573. child: Text(
  2574. label,
  2575. style: const TextStyle(
  2576. color: Colors.black,
  2577. fontSize: 11,
  2578. fontWeight: FontWeight.w700,
  2579. ),
  2580. ),
  2581. ),
  2582. CustomPaint(
  2583. size: const Size(8, 6),
  2584. painter: _BubbleArrowPainter(),
  2585. ),
  2586. ],
  2587. );
  2588. }
  2589. }
  2590. class _BubbleArrowPainter extends CustomPainter {
  2591. @override
  2592. void paint(Canvas canvas, Size size) {
  2593. final paint = Paint()..color = AppColors.brand;
  2594. final path = Path()
  2595. ..moveTo(0, 0)
  2596. ..lineTo(size.width / 2, size.height)
  2597. ..lineTo(size.width, 0)
  2598. ..close();
  2599. canvas.drawPath(path, paint);
  2600. }
  2601. @override
  2602. bool shouldRepaint(_BubbleArrowPainter _) => false;
  2603. }
  2604. class _TpslSection extends StatelessWidget {
  2605. const _TpslSection({
  2606. required this.enabled,
  2607. required this.onToggle,
  2608. required this.tpController,
  2609. required this.slController,
  2610. });
  2611. final bool enabled;
  2612. final VoidCallback onToggle;
  2613. final TextEditingController tpController;
  2614. final TextEditingController slController;
  2615. @override
  2616. Widget build(BuildContext context) {
  2617. final cs = Theme.of(context).colorScheme;
  2618. return Column(
  2619. children: [
  2620. GestureDetector(
  2621. onTap: onToggle,
  2622. child: Row(
  2623. children: [
  2624. Container(
  2625. width: 16,
  2626. height: 16,
  2627. decoration: BoxDecoration(
  2628. borderRadius: BorderRadius.circular(4),
  2629. border: Border.all(
  2630. color:
  2631. enabled ? AppColors.brand : cs.onSurface.withAlpha(153),
  2632. width: 1.5,
  2633. ),
  2634. color: enabled ? AppColors.brand : Colors.transparent,
  2635. ),
  2636. child: enabled
  2637. ? const Icon(Icons.check, size: 12, color: Colors.black)
  2638. : null,
  2639. ),
  2640. const SizedBox(width: 6),
  2641. Text(AppLocalizations.of(context)!.takeProfitStopLoss,
  2642. style: TextStyle(color: cs.onSurface, fontSize: 13)),
  2643. ],
  2644. ),
  2645. ),
  2646. if (enabled) ...[
  2647. const SizedBox(height: 6),
  2648. _SmallInput(
  2649. controller: tpController,
  2650. hint: '${AppLocalizations.of(context)!.takeProfitPrice} (USDT)',
  2651. ),
  2652. const SizedBox(height: 4),
  2653. _SmallInput(
  2654. controller: slController,
  2655. hint: '${AppLocalizations.of(context)!.stopLossPrice} (USDT)',
  2656. ),
  2657. ],
  2658. ],
  2659. );
  2660. }
  2661. }
  2662. class _SmallInput extends StatefulWidget {
  2663. const _SmallInput({required this.controller, required this.hint});
  2664. final TextEditingController controller;
  2665. final String hint;
  2666. @override
  2667. State<_SmallInput> createState() => _SmallInputState();
  2668. }
  2669. class _SmallInputState extends State<_SmallInput> {
  2670. final _focusNode = FocusNode();
  2671. @override
  2672. void initState() {
  2673. super.initState();
  2674. _focusNode.addListener(() {
  2675. if (mounted) setState(() {});
  2676. });
  2677. }
  2678. @override
  2679. void dispose() {
  2680. _focusNode.dispose();
  2681. super.dispose();
  2682. }
  2683. @override
  2684. Widget build(BuildContext context) {
  2685. final cs = Theme.of(context).colorScheme;
  2686. final isDark = Theme.of(context).brightness == Brightness.dark;
  2687. final isFocused = _focusNode.hasFocus;
  2688. final bgColor = isFocused
  2689. ? (isDark ? AppColors.darkBgSecondary : Colors.white)
  2690. : (isDark ? AppColors.darkBgTertiary : AppColors.lightBgSecondary);
  2691. final activeBorder = isDark
  2692. ? AppColors.darkTextPrimary.withAlpha(200)
  2693. : const Color(0xFF383838);
  2694. return Container(
  2695. height: 34,
  2696. padding: const EdgeInsets.symmetric(horizontal: 10),
  2697. decoration: BoxDecoration(
  2698. color: bgColor,
  2699. borderRadius: BorderRadius.circular(6),
  2700. border: isFocused ? Border.all(color: activeBorder, width: 1.5) : null,
  2701. ),
  2702. child: TextField(
  2703. controller: widget.controller,
  2704. focusNode: _focusNode,
  2705. keyboardType: const TextInputType.numberWithOptions(decimal: true),
  2706. style: TextStyle(color: cs.onSurface, fontSize: 12),
  2707. decoration: InputDecoration(
  2708. hintText: widget.hint,
  2709. hintStyle:
  2710. TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 12),
  2711. border: InputBorder.none,
  2712. focusedBorder: InputBorder.none,
  2713. enabledBorder: InputBorder.none,
  2714. filled: false,
  2715. isDense: true,
  2716. contentPadding:
  2717. const EdgeInsets.symmetric(vertical: 8, horizontal: 0),
  2718. ),
  2719. ),
  2720. );
  2721. }
  2722. }
  2723. // 资金费率行 — 只订阅 fundingRate + fundingCountdown,每秒更新一次,不触发盘口重建
  2724. class _FundingRateRow extends ConsumerWidget {
  2725. const _FundingRateRow({required this.symbol});
  2726. final String symbol;
  2727. @override
  2728. Widget build(BuildContext context, WidgetRef ref) {
  2729. final cs = Theme.of(context).colorScheme;
  2730. final provider = futuresProvider(symbol);
  2731. final fundingRate = ref.watch(provider.select((s) => s.fundingRate));
  2732. final fundingCountdown =
  2733. ref.watch(provider.select((s) => s.fundingCountdown));
  2734. return Row(
  2735. mainAxisAlignment: MainAxisAlignment.end,
  2736. children: [
  2737. Column(
  2738. crossAxisAlignment: CrossAxisAlignment.end,
  2739. children: [
  2740. Text(AppLocalizations.of(context)!.fundingRateCountdown,
  2741. style: TextStyle(
  2742. color: cs.onSurface.withAlpha(153), fontSize: 11)),
  2743. Text(
  2744. '${fundingRate >= 0 ? '+' : ''}${(fundingRate * 100).toStringAsFixed(4)}% / $fundingCountdown',
  2745. style: TextStyle(
  2746. color: cs.onSurface,
  2747. fontSize: 13,
  2748. fontFeatures: const [FontFeature.tabularFigures()]),
  2749. ),
  2750. ],
  2751. ),
  2752. ],
  2753. );
  2754. }
  2755. }
  2756. class _OrderBookPanel extends ConsumerStatefulWidget {
  2757. const _OrderBookPanel({
  2758. required this.symbol,
  2759. required this.rowCount,
  2760. this.rowHeight = 22.0,
  2761. this.onPriceTap,
  2762. });
  2763. final String symbol;
  2764. final int rowCount;
  2765. final double rowHeight;
  2766. final ValueChanged<double>? onPriceTap;
  2767. @override
  2768. ConsumerState<_OrderBookPanel> createState() => _OrderBookPanelState();
  2769. }
  2770. /// 预计算后的单行盘口数据,避免 build() 内重复调用格式化函数
  2771. class _BookRowData {
  2772. const _BookRowData({
  2773. required this.price,
  2774. required this.qty,
  2775. required this.formattedPrice,
  2776. required this.depthPercent,
  2777. });
  2778. final double price;
  2779. final double qty;
  2780. final String formattedPrice;
  2781. final double depthPercent;
  2782. }
  2783. class _OrderBookPanelState extends ConsumerState<_OrderBookPanel> {
  2784. // 订单薄显示模式: 0=双向, 1=仅卖盘, 2=仅买盘
  2785. int _bookMode = 0;
  2786. // 缓存:只在 rawAsks/rawBids/bookMode 变化时重新计算
  2787. List<Map<String, dynamic>>? _prevAsks;
  2788. List<Map<String, dynamic>>? _prevBids;
  2789. int _prevBookMode = -1;
  2790. int _prevRowCount = -1;
  2791. int _prevPricePrecision = -1;
  2792. List<_BookRowData> _askRows = const [];
  2793. List<_BookRowData> _bidRows = const [];
  2794. double _bidRatio = 0.5;
  2795. void _recompute(
  2796. List<Map<String, dynamic>> rawAsks,
  2797. List<Map<String, dynamic>> rawBids,
  2798. double minTick,
  2799. int decimalDigits,
  2800. ) {
  2801. _prevAsks = rawAsks;
  2802. _prevBids = rawBids;
  2803. _prevBookMode = _bookMode;
  2804. _prevRowCount = widget.rowCount;
  2805. _prevPricePrecision = decimalDigits;
  2806. final aggAsks = _bookMode == 2 ? <Map<String, dynamic>>[] : rawAsks;
  2807. final aggBids = _bookMode == 1 ? <Map<String, dynamic>>[] : rawBids;
  2808. final askRows = _bookMode == 2
  2809. ? 0
  2810. : (_bookMode == 1 ? widget.rowCount * 2 : widget.rowCount);
  2811. final bidRows = _bookMode == 1
  2812. ? 0
  2813. : (_bookMode == 2 ? widget.rowCount * 2 : widget.rowCount);
  2814. final askSlice = aggAsks.take(askRows).toList();
  2815. final bidSlice = aggBids.take(bidRows).toList();
  2816. double totalAsk = 0, totalBid = 0, maxQ = 0.001;
  2817. for (var e in askSlice) {
  2818. final q = _toDouble(e['quantity']);
  2819. totalAsk += q;
  2820. if (q > maxQ) maxQ = q;
  2821. }
  2822. for (var e in bidSlice) {
  2823. final q = _toDouble(e['quantity']);
  2824. totalBid += q;
  2825. if (q > maxQ) maxQ = q;
  2826. }
  2827. final total = totalAsk + totalBid;
  2828. _bidRatio = total > 0 ? totalBid / total : 0.5;
  2829. // 卖盘:slice 升序,UI 反转(最高价在顶)
  2830. _askRows = List.generate(askRows, (i) {
  2831. final ri = askSlice.length - 1 - i;
  2832. if (ri < 0)
  2833. return const _BookRowData(
  2834. price: 0, qty: 0, formattedPrice: '', depthPercent: 0);
  2835. final price = _toDouble(askSlice[ri]['price']);
  2836. final qty = _toDouble(askSlice[ri]['quantity']);
  2837. return _BookRowData(
  2838. price: price,
  2839. qty: qty,
  2840. formattedPrice: _fmtPrice(price, minTick, decimalDigits),
  2841. depthPercent: qty / maxQ,
  2842. );
  2843. });
  2844. _bidRows = List.generate(bidRows, (i) {
  2845. if (i >= bidSlice.length)
  2846. return const _BookRowData(
  2847. price: 0, qty: 0, formattedPrice: '', depthPercent: 0);
  2848. final price = _toDouble(bidSlice[i]['price']);
  2849. final qty = _toDouble(bidSlice[i]['quantity']);
  2850. return _BookRowData(
  2851. price: price,
  2852. qty: qty,
  2853. formattedPrice: _fmtPrice(price, minTick, decimalDigits),
  2854. depthPercent: qty / maxQ,
  2855. );
  2856. });
  2857. }
  2858. // 根据合约价格精度计算小数位数
  2859. int _decimalDigits(int pricePrecision) {
  2860. if (pricePrecision <= 0) return 0;
  2861. return pricePrecision;
  2862. }
  2863. // 将价格按精度对齐(始终使用合约最小精度档)
  2864. double _roundToPrecision(double price, double minTick) {
  2865. return (price / minTick).round() * minTick;
  2866. }
  2867. String _fmtPrice(double price, double minTick, int decimalDigits) {
  2868. final str = price.toString();
  2869. // 如果原始字符串中有小数点,直接返回;否则返回固定格式
  2870. return str.contains('.') ? str : price.toStringAsFixed(0);
  2871. }
  2872. // 将原始订单列表按精度合并:相同价格档位的数量求和
  2873. // isSell=true → 按价格升序(卖盘,低价在前)
  2874. // isSell=false → 按价格降序(买盘,高价在前)
  2875. List<Map<String, dynamic>> _aggregate(
  2876. List<Map<String, dynamic>> raw, bool isSell, double minTick) {
  2877. final Map<double, double> bucket = {};
  2878. for (final o in raw) {
  2879. final p = _toDouble(o['price']);
  2880. final q = _toDouble(o['quantity']);
  2881. if (p <= 0 || q <= 0) continue;
  2882. final key = _roundToPrecision(p, minTick);
  2883. bucket[key] = (bucket[key] ?? 0) + q;
  2884. }
  2885. final entries = bucket.entries.toList()
  2886. ..sort((a, b) => isSell
  2887. ? a.key.compareTo(b.key) // 卖盘升序
  2888. : b.key.compareTo(a.key)); // 买盘降序
  2889. return entries.map((e) => {'price': e.key, 'quantity': e.value}).toList();
  2890. }
  2891. @override
  2892. Widget build(BuildContext context) {
  2893. final cs = Theme.of(context).colorScheme;
  2894. final provider = futuresProvider(widget.symbol);
  2895. final lastPrice = ref.watch(provider.select((s) => s.lastPrice));
  2896. final lastPriceStr = ref.watch(provider.select((s) => s.lastPriceStr));
  2897. final rawAsks = ref.watch(provider.select((s) => s.orderBookAsks));
  2898. final rawBids = ref.watch(provider.select((s) => s.orderBookBids));
  2899. final pricePrecision = ref.watch(provider.select((s) => s.pricePrecision));
  2900. final decimalDigits = _decimalDigits(pricePrecision);
  2901. final minTick = pricePrecision >= 0
  2902. ? pow(10, pricePrecision).toDouble()
  2903. : 1.0 / pow(10, -pricePrecision).toDouble();
  2904. // 只在数据或模式变化时重新计算行数据(避免每帧重复 O(n) 工作)
  2905. if (!identical(rawAsks, _prevAsks) ||
  2906. !identical(rawBids, _prevBids) ||
  2907. _bookMode != _prevBookMode ||
  2908. widget.rowCount != _prevRowCount ||
  2909. decimalDigits != _prevPricePrecision) {
  2910. _recompute(rawAsks, rawBids, minTick, decimalDigits);
  2911. }
  2912. final askRatio = 1.0 - _bidRatio;
  2913. final labelStyle =
  2914. TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 11);
  2915. return Padding(
  2916. padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
  2917. child: Column(
  2918. crossAxisAlignment: CrossAxisAlignment.start,
  2919. mainAxisSize: MainAxisSize.max,
  2920. children: [
  2921. // 资金费率独立 widget,每秒重建,不影响盘口行
  2922. RepaintBoundary(child: _FundingRateRow(symbol: widget.symbol)),
  2923. const SizedBox(height: 2),
  2924. Row(
  2925. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  2926. children: [
  2927. Flexible(
  2928. child: Text(AppLocalizations.of(context)!.priceUsdt,
  2929. overflow: TextOverflow.ellipsis, style: labelStyle)),
  2930. const SizedBox(width: 4),
  2931. Flexible(
  2932. child: Text(
  2933. AppLocalizations.of(context)!
  2934. .amountLabel2(_baseCoin(widget.symbol)),
  2935. overflow: TextOverflow.ellipsis,
  2936. style: labelStyle)),
  2937. ],
  2938. ),
  2939. const SizedBox(height: 4),
  2940. // 卖盘
  2941. if (_bookMode != 2)
  2942. for (var i = 0; i < _askRows.length; i++)
  2943. _askRows[i].price > 0
  2944. ? RepaintBoundary(
  2945. key: ValueKey('ask_$i'),
  2946. child: _BookRow(
  2947. price: _askRows[i].price,
  2948. isSell: true,
  2949. amount: _askRows[i].qty.toStringAsFixed(4),
  2950. depthPercent: _askRows[i].depthPercent,
  2951. formattedPrice: _askRows[i].formattedPrice,
  2952. rowHeight: widget.rowHeight,
  2953. onTap: widget.onPriceTap != null
  2954. ? () => widget.onPriceTap!(_askRows[i].price)
  2955. : null,
  2956. ),
  2957. )
  2958. : _BookRowPlaceholder(
  2959. key: ValueKey('ask_ph_$i'), rowHeight: widget.rowHeight),
  2960. Padding(
  2961. padding: const EdgeInsets.symmetric(vertical: 5),
  2962. child: FittedBox(
  2963. fit: BoxFit.scaleDown,
  2964. alignment: Alignment.centerLeft,
  2965. child: Row(
  2966. mainAxisSize: MainAxisSize.min,
  2967. crossAxisAlignment: CrossAxisAlignment.end,
  2968. children: [
  2969. Text(
  2970. lastPriceStr != null
  2971. ? formatRawPrice(lastPriceStr)
  2972. : formatPrice(lastPrice),
  2973. maxLines: 1,
  2974. overflow: TextOverflow.clip,
  2975. style: TextStyle(
  2976. color: cs.onSurface,
  2977. fontSize: 16,
  2978. fontWeight: FontWeight.w700,
  2979. fontFeatures: const [FontFeature.tabularFigures()],
  2980. ),
  2981. ),
  2982. const SizedBox(width: 4),
  2983. Text(
  2984. '≈\$${formatPrice(lastPrice * 0.9999)}',
  2985. maxLines: 1,
  2986. overflow: TextOverflow.clip,
  2987. style: TextStyle(
  2988. color: cs.onSurface.withAlpha(153),
  2989. fontSize: 10,
  2990. fontFeatures: const [FontFeature.tabularFigures()],
  2991. ),
  2992. ),
  2993. ],
  2994. ),
  2995. ),
  2996. ),
  2997. // 买盘
  2998. if (_bookMode != 1)
  2999. for (var i = 0; i < _bidRows.length; i++)
  3000. _bidRows[i].price > 0
  3001. ? RepaintBoundary(
  3002. key: ValueKey('bid_$i'),
  3003. child: _BookRow(
  3004. price: _bidRows[i].price,
  3005. isSell: false,
  3006. amount: _bidRows[i].qty.toStringAsFixed(4),
  3007. depthPercent: _bidRows[i].depthPercent,
  3008. formattedPrice: _bidRows[i].formattedPrice,
  3009. rowHeight: widget.rowHeight,
  3010. onTap: widget.onPriceTap != null
  3011. ? () => widget.onPriceTap!(_bidRows[i].price)
  3012. : null,
  3013. ),
  3014. )
  3015. : _BookRowPlaceholder(
  3016. key: ValueKey('bid_ph_$i'), rowHeight: widget.rowHeight),
  3017. const Spacer(), // 撑开剩余空间,让底部元素贴底
  3018. ClipRRect(
  3019. borderRadius: BorderRadius.circular(2),
  3020. child: Row(
  3021. children: [
  3022. Flexible(
  3023. flex: (_bidRatio * 100).round().clamp(1, 99),
  3024. child: Container(
  3025. height: 4, color: AppColors.rise.withAlpha(180)),
  3026. ),
  3027. Flexible(
  3028. flex: (askRatio * 100).round().clamp(1, 99),
  3029. child: Container(
  3030. height: 4, color: AppColors.fall.withAlpha(180)),
  3031. ),
  3032. ],
  3033. ),
  3034. ),
  3035. Row(
  3036. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  3037. children: [
  3038. Text('${(_bidRatio * 100).toStringAsFixed(2)}%',
  3039. style: const TextStyle(color: AppColors.rise, fontSize: 10)),
  3040. Text('${(askRatio * 100).toStringAsFixed(2)}%',
  3041. style: const TextStyle(color: AppColors.fall, fontSize: 10)),
  3042. ],
  3043. ),
  3044. const SizedBox(height: 2),
  3045. Row(
  3046. children: [
  3047. const Spacer(),
  3048. // 订单薄模式切换
  3049. GestureDetector(
  3050. onTap: () => setState(() => _bookMode = (_bookMode + 1) % 3),
  3051. child: Container(
  3052. width: 28,
  3053. height: 20,
  3054. padding:
  3055. const EdgeInsets.symmetric(horizontal: 3, vertical: 2),
  3056. decoration: BoxDecoration(
  3057. border: Border.all(color: cs.outline.withAlpha(80)),
  3058. borderRadius: BorderRadius.circular(4),
  3059. ),
  3060. child: _BookModeIcon(mode: _bookMode),
  3061. ),
  3062. ),
  3063. ],
  3064. ),
  3065. ],
  3066. ),
  3067. );
  3068. }
  3069. }
  3070. class _BookRow extends StatelessWidget {
  3071. const _BookRow({
  3072. super.key,
  3073. required this.price,
  3074. required this.isSell,
  3075. required this.amount,
  3076. this.depthPercent = 0.3,
  3077. this.formattedPrice,
  3078. this.rowHeight = 22.0,
  3079. this.onTap,
  3080. });
  3081. final double price;
  3082. final bool isSell;
  3083. final String amount;
  3084. final double depthPercent;
  3085. final String? formattedPrice;
  3086. final double rowHeight;
  3087. final VoidCallback? onTap;
  3088. @override
  3089. Widget build(BuildContext context) {
  3090. final cs = Theme.of(context).colorScheme;
  3091. final color = isSell ? AppColors.fall : AppColors.rise;
  3092. return GestureDetector(
  3093. onTap: onTap,
  3094. behavior: HitTestBehavior.opaque,
  3095. child: SizedBox(
  3096. height: rowHeight,
  3097. child: LayoutBuilder(
  3098. builder: (_, constraints) {
  3099. final barW = constraints.maxWidth * depthPercent.clamp(0.0, 1.0);
  3100. return Stack(
  3101. children: [
  3102. Positioned(
  3103. right: 0,
  3104. top: 1,
  3105. bottom: 1,
  3106. child: AnimatedContainer(
  3107. duration: const Duration(milliseconds: 300),
  3108. curve: Curves.easeOut,
  3109. width: barW,
  3110. decoration: BoxDecoration(
  3111. color: color.withAlpha(38),
  3112. borderRadius: BorderRadius.circular(2),
  3113. ),
  3114. ),
  3115. ),
  3116. Padding(
  3117. padding: const EdgeInsets.symmetric(vertical: 1),
  3118. child: Row(
  3119. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  3120. children: [
  3121. Text(formattedPrice ?? formatPrice(price),
  3122. style: TextStyle(
  3123. color: color,
  3124. fontSize: 13,
  3125. fontWeight: FontWeight.w500,
  3126. fontFeatures: const [
  3127. FontFeature.tabularFigures()
  3128. ])),
  3129. Text(amount,
  3130. style: TextStyle(
  3131. color: cs.onSurface,
  3132. fontSize: 13,
  3133. fontFeatures: const [
  3134. FontFeature.tabularFigures()
  3135. ])),
  3136. ],
  3137. ),
  3138. ),
  3139. ],
  3140. );
  3141. },
  3142. ),
  3143. ),
  3144. );
  3145. }
  3146. }
  3147. /// 订单薄模式图标:3种视觉样式
  3148. /// mode=0 双向 | mode=1 仅卖盘 | mode=2 仅买盘
  3149. class _BookModeIcon extends StatelessWidget {
  3150. const _BookModeIcon({required this.mode});
  3151. final int mode;
  3152. @override
  3153. Widget build(BuildContext context) {
  3154. const sellColor = AppColors.fall;
  3155. const buyColor = AppColors.rise;
  3156. const emptyColor = Color(0xFFCCCCCC);
  3157. final double lineH = 2.0;
  3158. final double gap = 1.5;
  3159. Widget line(Color color) => Container(
  3160. height: lineH,
  3161. decoration: BoxDecoration(
  3162. color: color,
  3163. borderRadius: BorderRadius.circular(1),
  3164. ),
  3165. );
  3166. // 3 lines: top=sell side, bottom=buy side
  3167. // mode0: top 1.5 sell lines + 1.5 buy lines
  3168. // mode1: all sell (red)
  3169. // mode2: all buy (green)
  3170. final List<Widget> lines;
  3171. if (mode == 0) {
  3172. lines = [
  3173. line(sellColor),
  3174. SizedBox(height: gap),
  3175. line(sellColor),
  3176. SizedBox(height: gap),
  3177. line(buyColor),
  3178. SizedBox(height: gap),
  3179. line(buyColor),
  3180. ];
  3181. } else if (mode == 1) {
  3182. lines = [
  3183. line(sellColor),
  3184. SizedBox(height: gap),
  3185. line(sellColor),
  3186. SizedBox(height: gap),
  3187. line(sellColor),
  3188. SizedBox(height: gap),
  3189. line(emptyColor),
  3190. ];
  3191. } else {
  3192. lines = [
  3193. line(emptyColor),
  3194. SizedBox(height: gap),
  3195. line(buyColor),
  3196. SizedBox(height: gap),
  3197. line(buyColor),
  3198. SizedBox(height: gap),
  3199. line(buyColor),
  3200. ];
  3201. }
  3202. return Column(
  3203. mainAxisAlignment: MainAxisAlignment.center,
  3204. crossAxisAlignment: CrossAxisAlignment.stretch,
  3205. children: lines,
  3206. );
  3207. }
  3208. }
  3209. /// 无数据时的占位行,高度与 _BookRow 保持一致
  3210. class _BookRowPlaceholder extends StatelessWidget {
  3211. const _BookRowPlaceholder({super.key, this.rowHeight = 22.0});
  3212. final double rowHeight;
  3213. @override
  3214. Widget build(BuildContext context) {
  3215. return AppShimmer(
  3216. child: SizedBox(
  3217. height: rowHeight,
  3218. child: Row(
  3219. children: [
  3220. Expanded(
  3221. child: Align(
  3222. alignment: Alignment.centerLeft,
  3223. child: shimmerBox(60, 10),
  3224. )),
  3225. Expanded(
  3226. child: Align(
  3227. alignment: Alignment.centerRight,
  3228. child: shimmerBox(50, 10),
  3229. )),
  3230. ],
  3231. ),
  3232. ),
  3233. );
  3234. }
  3235. }
  3236. // ── 自适应高度辅助 ─────────────────────────────────────────
  3237. // 用 OverflowBox 解除父级高度约束,让子内容按自然高度布局,
  3238. // 再通过 addPostFrameCallback 读取真实 RenderBox 高度上报给父级。
  3239. // PageView 本身会 clip,所以 OverflowBox 超出部分不会显示。
  3240. class _MeasureSize extends StatefulWidget {
  3241. const _MeasureSize({required this.child, required this.onSize});
  3242. final Widget child;
  3243. final ValueChanged<double> onSize;
  3244. @override
  3245. State<_MeasureSize> createState() => _MeasureSizeState();
  3246. }
  3247. class _MeasureSizeState extends State<_MeasureSize> {
  3248. final _key = GlobalKey();
  3249. double? _last;
  3250. @override
  3251. Widget build(BuildContext context) {
  3252. WidgetsBinding.instance.addPostFrameCallback((_) {
  3253. if (!mounted) return;
  3254. final box = _key.currentContext?.findRenderObject() as RenderBox?;
  3255. if (box == null || !box.hasSize) return;
  3256. final h = box.size.height;
  3257. if (h != _last) {
  3258. _last = h;
  3259. widget.onSize(h);
  3260. }
  3261. });
  3262. // OverflowBox:宽度跟父级一致,高度不设上限,让子内容自由伸展。
  3263. // 这样 RenderBox.size.height 反映的是内容的真实高度,而不是父级约束高度。
  3264. return OverflowBox(
  3265. alignment: Alignment.topLeft,
  3266. minHeight: 0,
  3267. maxHeight: double.infinity,
  3268. child: KeyedSubtree(key: _key, child: widget.child),
  3269. );
  3270. }
  3271. }
  3272. class _BottomSection extends ConsumerStatefulWidget {
  3273. const _BottomSection({required this.symbol});
  3274. final String symbol;
  3275. @override
  3276. ConsumerState<_BottomSection> createState() => _BottomSectionState();
  3277. }
  3278. class _BottomSectionState extends ConsumerState<_BottomSection> {
  3279. late PageController _pageController;
  3280. bool _programmaticSwitch = false;
  3281. // 三个 Tab 各自测量到的高度。
  3282. // 初始值需能容纳 shimmer 占位内容(positions rows=2 ≈252px,orders rows=3 ≈380px,
  3283. // assets ≈260px),避免第一帧溢出。OverflowBox 测量到真实高度后会立即更新。
  3284. final _tabHeights = [280.0, 420.0, 280.0];
  3285. static int _tabToIndex(FuturesTab tab) {
  3286. switch (tab) {
  3287. case FuturesTab.positions:
  3288. return 0;
  3289. case FuturesTab.orders:
  3290. return 1;
  3291. case FuturesTab.assets:
  3292. return 2;
  3293. }
  3294. }
  3295. static FuturesTab _indexToTab(int index) {
  3296. switch (index) {
  3297. case 0:
  3298. return FuturesTab.positions;
  3299. case 1:
  3300. return FuturesTab.orders;
  3301. default:
  3302. return FuturesTab.assets;
  3303. }
  3304. }
  3305. @override
  3306. void initState() {
  3307. super.initState();
  3308. final initial = ref.read(futuresProvider(widget.symbol)).activeTab;
  3309. _pageController = PageController(initialPage: _tabToIndex(initial));
  3310. }
  3311. @override
  3312. void dispose() {
  3313. _pageController.dispose();
  3314. super.dispose();
  3315. }
  3316. void _onTabTap(FuturesTab tab) {
  3317. _programmaticSwitch = true;
  3318. ref.read(futuresProvider(widget.symbol).notifier).setTab(tab);
  3319. _pageController.animateToPage(
  3320. _tabToIndex(tab),
  3321. duration: const Duration(milliseconds: 280),
  3322. curve: Curves.easeOut,
  3323. );
  3324. }
  3325. @override
  3326. Widget build(BuildContext context) {
  3327. final cs = Theme.of(context).colorScheme;
  3328. final symbol = widget.symbol;
  3329. final provider = futuresProvider(symbol);
  3330. final activeTab = ref.watch(provider.select((s) => s.activeTab));
  3331. final positionsCount =
  3332. ref.watch(provider.select((s) => s.positions.length));
  3333. final ordersCount = ref.watch(provider.select((s) => s.openOrders.length));
  3334. final isTabLoading = ref.watch(provider.select((s) => s.isTabLoading));
  3335. return Container(
  3336. decoration: BoxDecoration(
  3337. border: Border(top: BorderSide(color: cs.outline)),
  3338. ),
  3339. child: Column(
  3340. children: [
  3341. // Tab 头
  3342. Padding(
  3343. padding: const EdgeInsets.symmetric(horizontal: 12),
  3344. child: Row(
  3345. children: [
  3346. _BottomTab(
  3347. label: AppLocalizations.of(context)!.positionsTab,
  3348. count: positionsCount > 0 ? '($positionsCount)' : null,
  3349. countColor: AppColors.fall,
  3350. active: activeTab == FuturesTab.positions,
  3351. onTap: () => _onTabTap(FuturesTab.positions),
  3352. ),
  3353. const SizedBox(width: 16),
  3354. _BottomTab(
  3355. label: AppLocalizations.of(context)!.currentOrders,
  3356. count: ordersCount > 0 ? '($ordersCount)' : null,
  3357. active: activeTab == FuturesTab.orders,
  3358. onTap: () => _onTabTap(FuturesTab.orders),
  3359. ),
  3360. const SizedBox(width: 16),
  3361. _BottomTab(
  3362. label: AppLocalizations.of(context)!.assets,
  3363. active: activeTab == FuturesTab.assets,
  3364. onTap: () => _onTabTap(FuturesTab.assets),
  3365. ),
  3366. const Spacer(),
  3367. GestureDetector(
  3368. onTap: () async {
  3369. final notifier = ref.read(futuresProvider(symbol).notifier);
  3370. notifier.stopPolling();
  3371. await context.push('/futures/$symbol/history');
  3372. if (context.mounted) notifier.resumePolling(symbol);
  3373. },
  3374. child: Icon(Icons.access_time,
  3375. color: cs.onSurface.withAlpha(153), size: 18),
  3376. ),
  3377. ],
  3378. ),
  3379. ),
  3380. // 工具栏(持仓/委托各有操作按钮)
  3381. AnimatedSwitcher(
  3382. duration: const Duration(milliseconds: 200),
  3383. child: activeTab == FuturesTab.positions
  3384. ? _PositionToolbar(
  3385. key: const ValueKey('pos_toolbar'), symbol: symbol)
  3386. : activeTab == FuturesTab.orders
  3387. ? _OrderToolbar(
  3388. key: const ValueKey('ord_toolbar'), symbol: symbol)
  3389. : const SizedBox.shrink(key: ValueKey('no_toolbar')),
  3390. ),
  3391. // 滑动内容区
  3392. // PageView 在 Column 内必须有有界高度。
  3393. // 通过 _MeasureSize 让每个 Tab 上报自身真实高度,取三者最大值,
  3394. // 避免硬编码估算值在内容变化时溢出。
  3395. SizedBox(
  3396. height: _tabHeights.reduce(max).clamp(100.0, 2000.0),
  3397. child: RepaintBoundary(
  3398. child: PageView(
  3399. controller: _pageController,
  3400. physics: const ClampingScrollPhysics(),
  3401. onPageChanged: (index) {
  3402. if (_programmaticSwitch) {
  3403. _programmaticSwitch = false;
  3404. return;
  3405. }
  3406. final tab = _indexToTab(index);
  3407. ref.read(futuresProvider(symbol).notifier).setTab(tab);
  3408. },
  3409. children: [
  3410. _MeasureSize(
  3411. onSize: (h) {
  3412. if (_tabHeights[0] != h)
  3413. setState(() => _tabHeights[0] = h);
  3414. },
  3415. child: _BottomTabContent(
  3416. symbol: symbol, tab: FuturesTab.positions),
  3417. ),
  3418. _MeasureSize(
  3419. onSize: (h) {
  3420. if (_tabHeights[1] != h)
  3421. setState(() => _tabHeights[1] = h);
  3422. },
  3423. child: _BottomTabContent(
  3424. symbol: symbol, tab: FuturesTab.orders),
  3425. ),
  3426. _MeasureSize(
  3427. onSize: (h) {
  3428. if (_tabHeights[2] != h)
  3429. setState(() => _tabHeights[2] = h);
  3430. },
  3431. child: _BottomTabContent(
  3432. symbol: symbol, tab: FuturesTab.assets),
  3433. ),
  3434. ],
  3435. ),
  3436. ),
  3437. ),
  3438. ],
  3439. ),
  3440. );
  3441. }
  3442. }
  3443. class _BottomTabContent extends ConsumerWidget {
  3444. const _BottomTabContent({required this.symbol, required this.tab});
  3445. final String symbol;
  3446. final FuturesTab tab;
  3447. @override
  3448. Widget build(BuildContext context, WidgetRef ref) {
  3449. final provider = futuresProvider(symbol);
  3450. final isTabLoading = ref.watch(provider.select((s) => s.isTabLoading));
  3451. switch (tab) {
  3452. case FuturesTab.positions:
  3453. final positions = ref.watch(provider.select((s) => s.displayPositions));
  3454. if (isTabLoading && positions.isEmpty)
  3455. return const _TabShimmer(rows: 2);
  3456. return _PositionsList(symbol: symbol, positions: positions);
  3457. case FuturesTab.orders:
  3458. final openOrders = ref.watch(provider.select((s) => s.displayOrders));
  3459. if (isTabLoading && openOrders.isEmpty)
  3460. return const _TabShimmer(rows: 3);
  3461. return _OrdersList(symbol: symbol, orders: openOrders);
  3462. case FuturesTab.assets:
  3463. final accountInfo = ref.watch(provider.select((s) => s.accountInfo));
  3464. if (isTabLoading && accountInfo.totalBalance == 0)
  3465. return const _AssetShimmer();
  3466. return _AssetsPanel(info: accountInfo);
  3467. }
  3468. }
  3469. }
  3470. class _PositionToolbar extends ConsumerWidget {
  3471. const _PositionToolbar({super.key, required this.symbol});
  3472. final String symbol;
  3473. @override
  3474. Widget build(BuildContext context, WidgetRef ref) {
  3475. final cs = Theme.of(context).colorScheme;
  3476. final notifier = ref.read(futuresProvider(symbol).notifier);
  3477. final hideOther =
  3478. ref.watch(futuresProvider(symbol).select((s) => s.hideOtherSymbols));
  3479. return Padding(
  3480. padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
  3481. child: Row(
  3482. children: [
  3483. GestureDetector(
  3484. onTap: notifier.toggleHideOtherSymbols,
  3485. child: Row(
  3486. children: [
  3487. _CheckBox(checked: hideOther),
  3488. const SizedBox(width: 4),
  3489. Text(AppLocalizations.of(context)!.hideOtherPairs,
  3490. style: TextStyle(
  3491. color: cs.onSurface.withAlpha(153), fontSize: 11)),
  3492. ],
  3493. ),
  3494. ),
  3495. const Spacer(),
  3496. GestureDetector(
  3497. onTap: () => _closeAll(context, ref, notifier),
  3498. child: Container(
  3499. padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
  3500. decoration: BoxDecoration(
  3501. color: cs.inverseSurface,
  3502. borderRadius: BorderRadius.circular(4),
  3503. ),
  3504. child: Text(AppLocalizations.of(context)!.closeAllPositions,
  3505. style: TextStyle(
  3506. color: cs.onInverseSurface,
  3507. fontSize: 11,
  3508. fontWeight: FontWeight.w500)),
  3509. ),
  3510. ),
  3511. ],
  3512. ),
  3513. );
  3514. }
  3515. Future<void> _closeAll(
  3516. BuildContext context, WidgetRef ref, FuturesNotifier notifier) async {
  3517. if (!_requireLogin(context, ref)) return;
  3518. final l10n = AppLocalizations.of(context)!;
  3519. final confirmed = await _showFuturesConfirm(
  3520. context,
  3521. message: l10n.closeAllConfirm,
  3522. subMessage: l10n.closeAllSubMsg,
  3523. );
  3524. if (!confirmed || !context.mounted) return;
  3525. final err = await notifier.closeAllPositions();
  3526. if (!context.mounted) return;
  3527. final l10n2 = AppLocalizations.of(context)!;
  3528. showTopToast(context,
  3529. message: resolveProviderError(err, l10n2) ?? l10n2.closeAllSubmitted,
  3530. backgroundColor: err != null ? AppColors.fall : AppColors.rise);
  3531. }
  3532. }
  3533. class _OrderToolbar extends ConsumerWidget {
  3534. const _OrderToolbar({super.key, required this.symbol});
  3535. final String symbol;
  3536. @override
  3537. Widget build(BuildContext context, WidgetRef ref) {
  3538. final cs = Theme.of(context).colorScheme;
  3539. final notifier = ref.read(futuresProvider(symbol).notifier);
  3540. final hideOther =
  3541. ref.watch(futuresProvider(symbol).select((s) => s.hideOtherSymbols));
  3542. return Padding(
  3543. padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
  3544. child: Row(
  3545. children: [
  3546. GestureDetector(
  3547. onTap: notifier.toggleHideOtherSymbols,
  3548. child: Row(
  3549. children: [
  3550. _CheckBox(checked: hideOther),
  3551. const SizedBox(width: 4),
  3552. Text(AppLocalizations.of(context)!.hideOtherPairs,
  3553. style: TextStyle(
  3554. color: cs.onSurface.withAlpha(153), fontSize: 11)),
  3555. ],
  3556. ),
  3557. ),
  3558. const Spacer(),
  3559. GestureDetector(
  3560. onTap: () => _cancelAll(context, ref, notifier),
  3561. child: Container(
  3562. padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
  3563. decoration: BoxDecoration(
  3564. color: cs.inverseSurface,
  3565. borderRadius: BorderRadius.circular(4),
  3566. ),
  3567. child: Text(AppLocalizations.of(context)!.cancelAllOrders,
  3568. style: TextStyle(
  3569. color: cs.onInverseSurface,
  3570. fontSize: 11,
  3571. fontWeight: FontWeight.w500)),
  3572. ),
  3573. ),
  3574. ],
  3575. ),
  3576. );
  3577. }
  3578. Future<void> _cancelAll(
  3579. BuildContext context, WidgetRef ref, FuturesNotifier notifier) async {
  3580. if (!_requireLogin(context, ref)) return;
  3581. final err = await notifier.cancelAllOrders();
  3582. if (!context.mounted) return;
  3583. final l10n3 = AppLocalizations.of(context)!;
  3584. showTopToast(context,
  3585. message: resolveProviderError(err, l10n3) ?? l10n3.cancelAllSuccess,
  3586. backgroundColor: err != null ? AppColors.fall : AppColors.rise);
  3587. }
  3588. }
  3589. class _BottomTab extends StatelessWidget {
  3590. const _BottomTab({
  3591. required this.label,
  3592. required this.active,
  3593. required this.onTap,
  3594. this.count,
  3595. this.countColor,
  3596. });
  3597. final String label;
  3598. final bool active;
  3599. final VoidCallback onTap;
  3600. /// 数量 badge 文字,如 "(2)"
  3601. final String? count;
  3602. /// badge 文字颜色,默认灰色
  3603. final Color? countColor;
  3604. @override
  3605. Widget build(BuildContext context) {
  3606. final cs = Theme.of(context).colorScheme;
  3607. final labelColor = active ? cs.onSurface : cs.onSurface.withAlpha(153);
  3608. return GestureDetector(
  3609. onTap: onTap,
  3610. child: Container(
  3611. padding: const EdgeInsets.symmetric(vertical: 10),
  3612. decoration: BoxDecoration(
  3613. border: Border(
  3614. bottom: BorderSide(
  3615. color: active ? AppColors.brand : Colors.transparent,
  3616. width: 2,
  3617. ),
  3618. ),
  3619. ),
  3620. child: count != null
  3621. ? RichText(
  3622. text: TextSpan(
  3623. children: [
  3624. TextSpan(
  3625. text: label,
  3626. style: TextStyle(
  3627. color: labelColor,
  3628. fontSize: 13,
  3629. fontWeight: active ? FontWeight.w600 : FontWeight.w400,
  3630. ),
  3631. ),
  3632. TextSpan(
  3633. text: count,
  3634. style: TextStyle(
  3635. color: countColor ?? cs.onSurface.withAlpha(153),
  3636. fontSize: 13,
  3637. fontWeight: active ? FontWeight.w600 : FontWeight.w400,
  3638. ),
  3639. ),
  3640. ],
  3641. ),
  3642. )
  3643. : Text(
  3644. label,
  3645. style: TextStyle(
  3646. color: labelColor,
  3647. fontSize: 13,
  3648. fontWeight: active ? FontWeight.w600 : FontWeight.w400,
  3649. ),
  3650. ),
  3651. ),
  3652. );
  3653. }
  3654. }
  3655. class _PositionsList extends StatelessWidget {
  3656. const _PositionsList({required this.symbol, required this.positions});
  3657. final String symbol;
  3658. final List<FuturesPosition> positions;
  3659. @override
  3660. Widget build(BuildContext context) {
  3661. final cs = Theme.of(context).colorScheme;
  3662. if (positions.isEmpty) {
  3663. return Padding(
  3664. padding: const EdgeInsets.symmetric(vertical: 40),
  3665. child: Center(
  3666. child: Text(AppLocalizations.of(context)!.noPositions,
  3667. style:
  3668. TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 13)),
  3669. ),
  3670. );
  3671. }
  3672. return ListView.builder(
  3673. padding: const EdgeInsets.fromLTRB(12, 4, 12, 8),
  3674. shrinkWrap: true,
  3675. physics: const NeverScrollableScrollPhysics(),
  3676. itemCount: positions.length,
  3677. itemBuilder: (_, i) => RepaintBoundary(
  3678. key: ValueKey('pos_${positions[i].id}'),
  3679. child: _PositionCard(symbol: symbol, position: positions[i]),
  3680. ),
  3681. );
  3682. }
  3683. }
  3684. class _PositionCard extends ConsumerWidget {
  3685. const _PositionCard({required this.symbol, required this.position});
  3686. final String symbol;
  3687. final FuturesPosition position;
  3688. @override
  3689. Widget build(BuildContext context, WidgetRef ref) {
  3690. final cs = Theme.of(context).colorScheme;
  3691. final notifier = ref.read(futuresProvider(symbol).notifier);
  3692. final coinSymbol = _baseCoin(position.symbol);
  3693. final isLong = position.side == OrderSide.long;
  3694. final pnlColor =
  3695. position.unrealizedPnl >= 0 ? AppColors.rise : AppColors.fall;
  3696. final sideColor = isLong ? AppColors.rise : AppColors.fall;
  3697. final coinName = coinSymbol;
  3698. // 扁平卡片:border-bottom 分割,padding 10 12,与原型 .pos-card 对齐
  3699. return GestureDetector(
  3700. onTap: () async {
  3701. notifier.stopPolling();
  3702. await context.push('/futures/$symbol/position-detail',
  3703. extra: position);
  3704. if (context.mounted) notifier.resumePolling(symbol);
  3705. },
  3706. child: Container(
  3707. decoration: BoxDecoration(
  3708. border: Border(bottom: BorderSide(color: cs.outline.withAlpha(50))),
  3709. ),
  3710. padding: const EdgeInsets.fromLTRB(12, 10, 12, 16),
  3711. child: Column(
  3712. crossAxisAlignment: CrossAxisAlignment.start,
  3713. children: [
  3714. // ── 标题行 ──────────────────────────────────────────
  3715. Row(
  3716. children: [
  3717. // 多/空 彩色徽标
  3718. Container(
  3719. padding:
  3720. const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
  3721. decoration: BoxDecoration(
  3722. color: sideColor,
  3723. borderRadius: BorderRadius.circular(3),
  3724. ),
  3725. child: Text(
  3726. isLong
  3727. ? AppLocalizations.of(context)!.openLong
  3728. : AppLocalizations.of(context)!.openShort,
  3729. style: const TextStyle(
  3730. color: Colors.white,
  3731. fontSize: 11,
  3732. fontWeight: FontWeight.w700),
  3733. ),
  3734. ),
  3735. const SizedBox(width: 4),
  3736. // Expanded 包裹所有中间信息,分享按钮固定在最右
  3737. Expanded(
  3738. child: Row(
  3739. children: [
  3740. Flexible(
  3741. child: Text(
  3742. '${coinName}USDT',
  3743. maxLines: 1,
  3744. overflow: TextOverflow.ellipsis,
  3745. style: TextStyle(
  3746. color: cs.onSurface,
  3747. fontSize: 13,
  3748. fontWeight: FontWeight.w700),
  3749. ),
  3750. ),
  3751. const SizedBox(width: 4),
  3752. _SmallTag(
  3753. text: AppLocalizations.of(context)!.perpetual),
  3754. const SizedBox(width: 3),
  3755. _SmallTag(
  3756. text: _marginModeLabel(position.marginMode,
  3757. AppLocalizations.of(context)!),
  3758. color: _marginModeColor(position.marginMode)),
  3759. const SizedBox(width: 3),
  3760. // 杠杆 黄色徽标
  3761. Container(
  3762. padding: const EdgeInsets.symmetric(
  3763. horizontal: 5, vertical: 1),
  3764. decoration: BoxDecoration(
  3765. color: AppColors.leverageGoldBg,
  3766. borderRadius: BorderRadius.circular(3),
  3767. ),
  3768. child: Text(
  3769. '${position.leverage.toInt()}X',
  3770. style: const TextStyle(
  3771. color: AppColors.leverageGold,
  3772. fontSize: 10,
  3773. fontWeight: FontWeight.w700),
  3774. ),
  3775. ),
  3776. ],
  3777. ),
  3778. ),
  3779. const SizedBox(width: 8),
  3780. // 分享按钮固定在最右
  3781. GestureDetector(
  3782. onTap: () => _sharePosition(context),
  3783. child: Icon(Icons.share_outlined,
  3784. size: 16, color: cs.onSurface.withAlpha(153)),
  3785. ),
  3786. ],
  3787. ),
  3788. const SizedBox(height: 8),
  3789. // ── 未实现盈亏 + 收益率 ──────────────────────────────
  3790. Row(
  3791. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  3792. crossAxisAlignment: CrossAxisAlignment.end,
  3793. children: [
  3794. Column(
  3795. crossAxisAlignment: CrossAxisAlignment.start,
  3796. children: [
  3797. Text(
  3798. '${AppLocalizations.of(context)!.unrealizedPnl} (USDT)',
  3799. style: TextStyle(
  3800. color: cs.onSurface.withAlpha(153), fontSize: 9)),
  3801. Text(
  3802. formatAmount(position.unrealizedPnl),
  3803. style: TextStyle(
  3804. color: pnlColor,
  3805. fontSize: 16,
  3806. fontWeight: FontWeight.w700),
  3807. ),
  3808. ],
  3809. ),
  3810. Column(
  3811. crossAxisAlignment: CrossAxisAlignment.end,
  3812. children: [
  3813. Text(AppLocalizations.of(context)!.returnRate,
  3814. style: TextStyle(
  3815. color: cs.onSurface.withAlpha(153), fontSize: 9)),
  3816. Text(
  3817. '${formatAmount(position.roe)}%',
  3818. style: TextStyle(
  3819. color: pnlColor,
  3820. fontSize: 13,
  3821. fontWeight: FontWeight.w600),
  3822. ),
  3823. ],
  3824. ),
  3825. ],
  3826. ),
  3827. const SizedBox(height: 6),
  3828. // ── 数据行 1 ────────────────────────────────────────
  3829. Row(
  3830. children: [
  3831. _DataCol(
  3832. label:
  3833. '${AppLocalizations.of(context)!.positionSize}($coinSymbol)',
  3834. value: formatQuantity(position.size),
  3835. align: CrossAxisAlignment.start),
  3836. _DataCol(
  3837. label:
  3838. '${AppLocalizations.of(context)!.marginLabel}(USDT)',
  3839. value: formatAmount(position.margin),
  3840. align: CrossAxisAlignment.center),
  3841. _DataCol(
  3842. label: AppLocalizations.of(context)!.marginRatioLabel,
  3843. value: '${formatAmount(position.marginRatio)}%',
  3844. align: CrossAxisAlignment.end),
  3845. ],
  3846. ),
  3847. const SizedBox(height: 4),
  3848. // ── 数据行 2 ────────────────────────────────────────
  3849. Row(
  3850. children: [
  3851. _DataCol(
  3852. label:
  3853. '${AppLocalizations.of(context)!.openAvgPrice}(USDT)',
  3854. value: formatPrice(position.entryPrice),
  3855. align: CrossAxisAlignment.start),
  3856. _DataCol(
  3857. label:
  3858. '${AppLocalizations.of(context)!.latestLabel}(USDT)',
  3859. value: formatPrice(position.markPrice),
  3860. align: CrossAxisAlignment.center),
  3861. _DataCol(
  3862. label: '${AppLocalizations.of(context)!.liqPrice}(USDT)',
  3863. value: position.liquidationPrice > 0
  3864. ? formatPrice(position.liquidationPrice)
  3865. : '--',
  3866. valueColor: position.liquidationPrice > 0
  3867. ? AppColors.fall
  3868. : cs.onSurface.withAlpha(153),
  3869. align: CrossAxisAlignment.end,
  3870. ),
  3871. ],
  3872. ),
  3873. const SizedBox(height: 8),
  3874. // ── 操作按钮 ──
  3875. Row(
  3876. children: [
  3877. _ActionBtn(
  3878. text: AppLocalizations.of(context)!.takeProfitStopLossBtn,
  3879. onTap: () => _showTpslSheet(context, ref, notifier)),
  3880. const SizedBox(width: 5),
  3881. _ActionBtn(
  3882. text: AppLocalizations.of(context)!.reversePositionBtn,
  3883. onTap: () => _reverse(context, ref, notifier)),
  3884. const SizedBox(width: 5),
  3885. _ActionBtn(
  3886. text: AppLocalizations.of(context)!.closePositionBtn,
  3887. onTap: () => _showCloseSheet(context, ref, notifier)),
  3888. const SizedBox(width: 5),
  3889. Expanded(
  3890. child: SizedBox(
  3891. height: 28,
  3892. child: ElevatedButton(
  3893. onPressed: () => _closeMarket(context, notifier),
  3894. style: ElevatedButton.styleFrom(
  3895. backgroundColor: AppColors.brand,
  3896. shape: RoundedRectangleBorder(
  3897. borderRadius: BorderRadius.circular(4)),
  3898. elevation: 0,
  3899. padding: EdgeInsets.zero,
  3900. ),
  3901. child: Text(
  3902. AppLocalizations.of(context)!.closeAllMarket,
  3903. style: const TextStyle(
  3904. color: Colors.black,
  3905. fontSize: 11,
  3906. fontWeight: FontWeight.w500)),
  3907. ),
  3908. ),
  3909. ),
  3910. ],
  3911. ),
  3912. ],
  3913. ),
  3914. )); // GestureDetector + Container
  3915. }
  3916. /// 分享仓位:弹出预览底部弹窗,用户确认后生成图片并调用系统分享
  3917. void _sharePosition(BuildContext context) {
  3918. showModalBottomSheet<void>(
  3919. context: context,
  3920. useRootNavigator: true,
  3921. backgroundColor: Colors.transparent,
  3922. isScrollControlled: true,
  3923. builder: (_) => SharePositionSheet(position: position),
  3924. );
  3925. }
  3926. Future<void> _closeMarket(
  3927. BuildContext context, FuturesNotifier notifier) async {
  3928. final l10n = AppLocalizations.of(context)!;
  3929. final confirmed = await _showFuturesConfirm(
  3930. context,
  3931. message: l10n.closeAllMarketConfirm,
  3932. subMessage: l10n.closeAllMarketSubMsg,
  3933. );
  3934. if (!confirmed || !context.mounted) return;
  3935. final err = await notifier.closeMarket(position);
  3936. if (!context.mounted) return;
  3937. final l10n4 = AppLocalizations.of(context)!;
  3938. showTopToast(context,
  3939. message:
  3940. resolveProviderError(err, l10n4) ?? l10n4.closeAllMarketSuccess,
  3941. backgroundColor: err != null ? AppColors.fall : AppColors.rise);
  3942. }
  3943. void _showCloseSheet(
  3944. BuildContext context, WidgetRef ref, FuturesNotifier notifier) {
  3945. if (!_requireLogin(context, ref)) return;
  3946. FocusScope.of(context).unfocus();
  3947. showModalBottomSheet<void>(
  3948. context: context,
  3949. useRootNavigator: true,
  3950. isScrollControlled: true,
  3951. backgroundColor: Theme.of(context).colorScheme.surface,
  3952. shape: const RoundedRectangleBorder(
  3953. borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
  3954. ),
  3955. builder: (_) => _ClosePositionSheet(
  3956. position: position, notifier: notifier, symbol: symbol),
  3957. );
  3958. }
  3959. void _showTpslSheet(
  3960. BuildContext context, WidgetRef ref, FuturesNotifier notifier) {
  3961. if (!_requireLogin(context, ref)) return;
  3962. FocusScope.of(context).unfocus();
  3963. final pricePrecision =
  3964. ref.read(futuresProvider(symbol).select((s) => s.pricePrecision));
  3965. showModalBottomSheet<void>(
  3966. context: context,
  3967. useRootNavigator: true,
  3968. isScrollControlled: true,
  3969. backgroundColor: Theme.of(context).colorScheme.surface,
  3970. shape: const RoundedRectangleBorder(
  3971. borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
  3972. ),
  3973. builder: (_) => _TpslSheet(
  3974. position: position,
  3975. notifier: notifier,
  3976. symbol: symbol,
  3977. pricePrecision: pricePrecision),
  3978. );
  3979. }
  3980. Future<void> _reverse(
  3981. BuildContext context, WidgetRef ref, FuturesNotifier notifier) async {
  3982. if (!_requireLogin(context, ref)) return;
  3983. final isLong = position.side == OrderSide.long;
  3984. final l10n = AppLocalizations.of(context)!;
  3985. final confirmed = await _showFuturesConfirm(
  3986. context,
  3987. message: l10n.reverseConfirm(
  3988. isLong ? l10n.longLabel : l10n.shortLabel,
  3989. isLong ? l10n.openShort : l10n.openLong,
  3990. ),
  3991. );
  3992. if (!confirmed || !context.mounted) return;
  3993. final err = await notifier.reversePosition(position);
  3994. if (!context.mounted) return;
  3995. final l10n5 = AppLocalizations.of(context)!;
  3996. showTopToast(context,
  3997. message: resolveProviderError(err, l10n5) ?? l10n5.reverseSuccess,
  3998. backgroundColor: err != null ? AppColors.fall : AppColors.rise);
  3999. }
  4000. }
  4001. /// 自定义 checkbox(方形边框,选中时填充品牌色+勾)
  4002. class _CheckBox extends StatelessWidget {
  4003. const _CheckBox({required this.checked});
  4004. final bool checked;
  4005. @override
  4006. Widget build(BuildContext context) {
  4007. final cs = Theme.of(context).colorScheme;
  4008. return Container(
  4009. width: 14,
  4010. height: 14,
  4011. decoration: BoxDecoration(
  4012. borderRadius: BorderRadius.circular(3),
  4013. color: checked ? AppColors.brand : Colors.transparent,
  4014. border: Border.all(
  4015. color: checked ? AppColors.brand : cs.onSurface.withAlpha(153),
  4016. width: 1,
  4017. ),
  4018. ),
  4019. child: checked
  4020. ? const Icon(Icons.check, size: 10, color: Colors.white)
  4021. : null,
  4022. );
  4023. }
  4024. }
  4025. class _DataCol extends StatelessWidget {
  4026. const _DataCol({
  4027. required this.label,
  4028. required this.value,
  4029. this.valueColor,
  4030. this.align = CrossAxisAlignment.start,
  4031. });
  4032. final String label;
  4033. final String value;
  4034. final Color? valueColor;
  4035. final CrossAxisAlignment align;
  4036. @override
  4037. Widget build(BuildContext context) {
  4038. final cs = Theme.of(context).colorScheme;
  4039. final textAlign = align == CrossAxisAlignment.end
  4040. ? TextAlign.right
  4041. : align == CrossAxisAlignment.center
  4042. ? TextAlign.center
  4043. : TextAlign.left;
  4044. return Expanded(
  4045. child: Column(
  4046. crossAxisAlignment: align,
  4047. children: [
  4048. Text(label,
  4049. maxLines: 1,
  4050. overflow: TextOverflow.ellipsis,
  4051. textAlign: textAlign,
  4052. style:
  4053. TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 9)),
  4054. Text(value,
  4055. maxLines: 1,
  4056. overflow: TextOverflow.ellipsis,
  4057. textAlign: textAlign,
  4058. style: TextStyle(
  4059. color: valueColor ?? cs.onSurface,
  4060. fontSize: 12,
  4061. fontWeight: FontWeight.w500)),
  4062. ],
  4063. ),
  4064. );
  4065. }
  4066. }
  4067. /// 委托卡片数据行:全宽,label 靠左,value 靠右
  4068. class _DataLine extends StatelessWidget {
  4069. const _DataLine({required this.label, required this.value, this.valueColor});
  4070. final String label;
  4071. final String value;
  4072. final Color? valueColor;
  4073. @override
  4074. Widget build(BuildContext context) {
  4075. final cs = Theme.of(context).colorScheme;
  4076. return Row(
  4077. children: [
  4078. Expanded(
  4079. child: Text(label,
  4080. maxLines: 1,
  4081. overflow: TextOverflow.ellipsis,
  4082. style:
  4083. TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 11)),
  4084. ),
  4085. Text(value,
  4086. maxLines: 1,
  4087. overflow: TextOverflow.ellipsis,
  4088. style: TextStyle(
  4089. color: valueColor ?? cs.onSurface,
  4090. fontSize: 11,
  4091. fontWeight: FontWeight.w500)),
  4092. ],
  4093. );
  4094. }
  4095. }
  4096. class _ActionBtn extends StatelessWidget {
  4097. const _ActionBtn({required this.text, required this.onTap});
  4098. final String text;
  4099. final VoidCallback onTap;
  4100. @override
  4101. Widget build(BuildContext context) {
  4102. final cs = Theme.of(context).colorScheme;
  4103. return Expanded(
  4104. child: SizedBox(
  4105. height: 28,
  4106. child: OutlinedButton(
  4107. onPressed: onTap,
  4108. style: OutlinedButton.styleFrom(
  4109. side: BorderSide(color: cs.outline),
  4110. shape:
  4111. RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
  4112. padding: EdgeInsets.zero,
  4113. ),
  4114. child: Text(text,
  4115. maxLines: 1,
  4116. overflow: TextOverflow.ellipsis,
  4117. style: TextStyle(
  4118. color: cs.onSurface,
  4119. fontSize: 11,
  4120. fontWeight: FontWeight.w500)),
  4121. ),
  4122. ),
  4123. );
  4124. }
  4125. }
  4126. /// 持仓卡片小标签(边框样式,对应原型 .pos-type-tag)
  4127. class _SmallTag extends StatelessWidget {
  4128. const _SmallTag({required this.text, this.color});
  4129. final String text;
  4130. final Color? color;
  4131. @override
  4132. Widget build(BuildContext context) {
  4133. final cs = Theme.of(context).colorScheme;
  4134. final isDark = Theme.of(context).brightness == Brightness.dark;
  4135. final c = color;
  4136. if (c != null) {
  4137. return Container(
  4138. padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
  4139. decoration: BoxDecoration(
  4140. color: c.withAlpha(isDark ? 45 : 25),
  4141. borderRadius: BorderRadius.circular(3),
  4142. ),
  4143. child: Text(text,
  4144. style:
  4145. TextStyle(color: c, fontSize: 9, fontWeight: FontWeight.w500)),
  4146. );
  4147. }
  4148. return Container(
  4149. padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
  4150. decoration: BoxDecoration(
  4151. border: Border.all(color: cs.outline.withAlpha(80), width: 0.5),
  4152. borderRadius: BorderRadius.circular(3),
  4153. ),
  4154. child: Text(
  4155. text,
  4156. style: TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 9),
  4157. ),
  4158. );
  4159. }
  4160. }
  4161. class _OrdersList extends ConsumerWidget {
  4162. const _OrdersList({required this.symbol, required this.orders});
  4163. final String symbol;
  4164. final List<FuturesOrder> orders;
  4165. @override
  4166. Widget build(BuildContext context, WidgetRef ref) {
  4167. final cs = Theme.of(context).colorScheme;
  4168. final hasMore =
  4169. ref.watch(futuresProvider(symbol).select((s) => s.ordersHasMore));
  4170. final loadingMore =
  4171. ref.watch(futuresProvider(symbol).select((s) => s.ordersLoadingMore));
  4172. if (orders.isEmpty) {
  4173. return Padding(
  4174. padding: const EdgeInsets.symmetric(vertical: 40),
  4175. child: Center(
  4176. child: Text(AppLocalizations.of(context)!.noOrders,
  4177. style:
  4178. TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 13)),
  4179. ),
  4180. );
  4181. }
  4182. final footerCount = (loadingMore || !hasMore) ? 1 : 0;
  4183. return ListView.builder(
  4184. padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
  4185. shrinkWrap: true,
  4186. physics: const NeverScrollableScrollPhysics(),
  4187. itemCount: orders.length + footerCount,
  4188. itemBuilder: (_, i) {
  4189. if (i < orders.length) {
  4190. return RepaintBoundary(
  4191. key: ValueKey('ord_${orders[i].id}'),
  4192. child: _OrderCard(symbol: symbol, order: orders[i]),
  4193. );
  4194. }
  4195. if (loadingMore) {
  4196. return const Padding(
  4197. padding: EdgeInsets.symmetric(vertical: 12),
  4198. child: Center(
  4199. child: SizedBox(
  4200. width: 16,
  4201. height: 16,
  4202. child: CircularProgressIndicator(strokeWidth: 2),
  4203. ),
  4204. ),
  4205. );
  4206. }
  4207. return Padding(
  4208. padding: const EdgeInsets.symmetric(vertical: 8),
  4209. child: Center(
  4210. child: Text(AppLocalizations.of(context)!.allLoaded,
  4211. style:
  4212. TextStyle(color: cs.onSurface.withAlpha(80), fontSize: 11)),
  4213. ),
  4214. );
  4215. },
  4216. );
  4217. }
  4218. }
  4219. class _OrderCard extends ConsumerWidget {
  4220. const _OrderCard({required this.symbol, required this.order});
  4221. final String symbol;
  4222. final FuturesOrder order;
  4223. @override
  4224. Widget build(BuildContext context, WidgetRef ref) {
  4225. final cs = Theme.of(context).colorScheme;
  4226. final notifier = ref.read(futuresProvider(symbol).notifier);
  4227. final coinSymbol = _baseCoin(order.symbol);
  4228. // 颜色规则:开多/平空=绿(买方向);开空/平多=红(卖方向)
  4229. final isOpen = order.isOpenOrder;
  4230. final isLong = order.side == OrderSide.long;
  4231. final actionColor = isOpen
  4232. ? (isLong ? AppColors.rise : AppColors.fall)
  4233. : (isLong ? AppColors.fall : AppColors.rise);
  4234. final hasProfit = order.profitPrice != null && order.profitPrice! > 0;
  4235. final hasLoss = order.lossPrice != null && order.lossPrice! > 0;
  4236. // 展示用价格:市价/计划市价→"市价",限价/计划限价→原始值
  4237. String _fmt(double v) =>
  4238. v == v.truncateToDouble() ? '${v.toInt()}' : v.toString();
  4239. final l10n = AppLocalizations.of(context)!;
  4240. final priceText = (order.type == OrderType.market ||
  4241. order.type == OrderType.conditionalMarket)
  4242. ? l10n.marketPrice
  4243. : (order.price > 0 ? _fmt(order.price) : '--');
  4244. // 对应原型 .order-card { border-bottom: 6px solid var(--color-bg-page) }
  4245. return GestureDetector(
  4246. onTap: () async {
  4247. notifier.stopPolling();
  4248. await context.push('/futures/$symbol/order-detail', extra: order);
  4249. if (context.mounted) notifier.resumePolling(symbol);
  4250. },
  4251. child: Container(
  4252. decoration: BoxDecoration(
  4253. border: Border(
  4254. bottom: BorderSide(
  4255. color: Theme.of(context).scaffoldBackgroundColor,
  4256. width: 6,
  4257. ),
  4258. ),
  4259. ),
  4260. padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
  4261. child: Column(
  4262. crossAxisAlignment: CrossAxisAlignment.start,
  4263. children: [
  4264. // ── 标题行(与持仓卡片结构一致)──────────────────────────
  4265. Row(
  4266. children: [
  4267. // 开多/开空/平多/平空 — 实心色块 chip
  4268. Container(
  4269. padding:
  4270. const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
  4271. decoration: BoxDecoration(
  4272. color: actionColor,
  4273. borderRadius: BorderRadius.circular(3),
  4274. ),
  4275. child: Text(
  4276. () {
  4277. final isLongSide = order.side == OrderSide.long;
  4278. if (isOpen)
  4279. return isLongSide ? l10n.openLong : l10n.openShort;
  4280. return isLongSide ? l10n.closeLong : l10n.closeShort;
  4281. }(),
  4282. style: const TextStyle(
  4283. color: Colors.white,
  4284. fontSize: 11,
  4285. fontWeight: FontWeight.w700),
  4286. ),
  4287. ),
  4288. const SizedBox(width: 4),
  4289. // Expanded 包裹币对+标签,撤单按钮固定在最右
  4290. Expanded(
  4291. child: Row(
  4292. children: [
  4293. Flexible(
  4294. child: Text(
  4295. order.symbol.toUpperCase(),
  4296. maxLines: 1,
  4297. overflow: TextOverflow.ellipsis,
  4298. style: TextStyle(
  4299. color: cs.onSurface,
  4300. fontSize: 13,
  4301. fontWeight: FontWeight.w700),
  4302. ),
  4303. ),
  4304. const SizedBox(width: 4),
  4305. _SmallTag(
  4306. text: order.type == OrderType.market
  4307. ? l10n.marketHint
  4308. : order.type == OrderType.limit
  4309. ? l10n.limitLabel
  4310. : l10n.planOrderLabel),
  4311. const SizedBox(width: 3),
  4312. _SmallTag(
  4313. text: _marginModeLabel(order.marginMode, l10n),
  4314. color: _marginModeColor(order.marginMode)),
  4315. const SizedBox(width: 3),
  4316. Container(
  4317. padding: const EdgeInsets.symmetric(
  4318. horizontal: 5, vertical: 1),
  4319. decoration: BoxDecoration(
  4320. color: AppColors.leverageGoldBg,
  4321. borderRadius: BorderRadius.circular(3),
  4322. ),
  4323. child: Text(
  4324. '${order.leverage.toInt()}X',
  4325. style: const TextStyle(
  4326. color: AppColors.leverageGold,
  4327. fontSize: 10,
  4328. fontWeight: FontWeight.w700),
  4329. ),
  4330. ),
  4331. if (hasProfit) ...[
  4332. const SizedBox(width: 4),
  4333. _TpSlChip(
  4334. label: l10n.takeProfit, color: AppColors.rise),
  4335. ],
  4336. if (hasLoss) ...[
  4337. const SizedBox(width: 4),
  4338. _TpSlChip(
  4339. label: l10n.stopLoss, color: AppColors.fall),
  4340. ],
  4341. ],
  4342. ),
  4343. ),
  4344. const SizedBox(width: 8),
  4345. // 撤单按钮固定在最右
  4346. GestureDetector(
  4347. onTap: () => _cancelOrder(context, ref, notifier),
  4348. child: Container(
  4349. padding: const EdgeInsets.symmetric(
  4350. horizontal: 8, vertical: 3),
  4351. decoration: BoxDecoration(
  4352. borderRadius: BorderRadius.circular(4),
  4353. border: Border.all(color: cs.outline),
  4354. ),
  4355. child: Text(l10n.cancelOrder,
  4356. style: TextStyle(color: cs.onSurface, fontSize: 11)),
  4357. ),
  4358. ),
  4359. ],
  4360. ),
  4361. const SizedBox(height: 8),
  4362. // ── 数据块(label 靠左,value 靠右,全宽行)────────────
  4363. _DataLine(label: l10n.orderPriceLabel, value: priceText),
  4364. const SizedBox(height: 3),
  4365. _DataLine(
  4366. label: l10n.orderSizeCoin(coinSymbol),
  4367. value: formatQuantity(order.size)),
  4368. const SizedBox(height: 3),
  4369. _DataLine(
  4370. label: l10n.filledSizeCoin(coinSymbol),
  4371. value: formatQuantity(order.filledSize)),
  4372. if (order.triggerPrice > 0) ...[
  4373. const SizedBox(height: 3),
  4374. _DataLine(
  4375. label: '${l10n.triggerPrice}(USDT)',
  4376. value: formatPrice(order.triggerPrice)),
  4377. ],
  4378. if (hasProfit) ...[
  4379. const SizedBox(height: 3),
  4380. _DataLine(
  4381. label: l10n.takeProfitPrice,
  4382. value: formatPrice(order.profitPrice!),
  4383. valueColor: AppColors.rise),
  4384. ],
  4385. if (hasLoss) ...[
  4386. const SizedBox(height: 3),
  4387. _DataLine(
  4388. label: l10n.stopLossPrice,
  4389. value: formatPrice(order.lossPrice!),
  4390. valueColor: AppColors.fall),
  4391. ],
  4392. ],
  4393. ),
  4394. )); // GestureDetector + Container
  4395. }
  4396. Future<void> _cancelOrder(
  4397. BuildContext context, WidgetRef ref, FuturesNotifier notifier) async {
  4398. if (!_requireLogin(context, ref)) return;
  4399. final err = await notifier.cancelOrder(order);
  4400. if (!context.mounted) return;
  4401. final l10n6 = AppLocalizations.of(context)!;
  4402. showTopToast(context,
  4403. message: resolveProviderError(err, l10n6) ?? l10n6.cancelOrderSuccess,
  4404. backgroundColor: err != null ? AppColors.fall : AppColors.rise);
  4405. }
  4406. }
  4407. /// 止盈止损指示小标签(行内 chip)
  4408. class _TpSlChip extends StatelessWidget {
  4409. const _TpSlChip({required this.label, required this.color});
  4410. final String label;
  4411. final Color color;
  4412. @override
  4413. Widget build(BuildContext context) {
  4414. return Container(
  4415. padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
  4416. decoration: BoxDecoration(
  4417. color: color.withAlpha(28),
  4418. borderRadius: BorderRadius.circular(3),
  4419. border: Border.all(color: color.withAlpha(120), width: 0.5),
  4420. ),
  4421. child: Text(
  4422. label,
  4423. style:
  4424. TextStyle(color: color, fontSize: 9, fontWeight: FontWeight.w600),
  4425. ),
  4426. );
  4427. }
  4428. }
  4429. class _TpslSheet extends ConsumerStatefulWidget {
  4430. const _TpslSheet(
  4431. {required this.position,
  4432. required this.notifier,
  4433. required this.symbol,
  4434. required this.pricePrecision});
  4435. final FuturesPosition position;
  4436. final FuturesNotifier notifier;
  4437. final String symbol;
  4438. final int pricePrecision;
  4439. @override
  4440. ConsumerState<_TpslSheet> createState() => _TpslSheetState();
  4441. }
  4442. class _TpslSheetState extends ConsumerState<_TpslSheet> {
  4443. late final TextEditingController _tpController;
  4444. late final TextEditingController _slController;
  4445. bool _tpEnabled = true;
  4446. bool _slEnabled = true;
  4447. @override
  4448. void initState() {
  4449. super.initState();
  4450. final pos = widget.position;
  4451. final p = widget.pricePrecision;
  4452. _tpController = TextEditingController(
  4453. text: pos.profitPrice != null && pos.profitPrice! > 0
  4454. ? pos.profitPrice!.toStringAsFixed(p)
  4455. : '');
  4456. _slController = TextEditingController(
  4457. text: pos.lossPrice != null && pos.lossPrice! > 0
  4458. ? pos.lossPrice!.toStringAsFixed(p)
  4459. : '');
  4460. _tpEnabled = pos.profitPrice != null && pos.profitPrice! > 0 ? true : true;
  4461. _slEnabled = pos.lossPrice != null && pos.lossPrice! > 0 ? true : true;
  4462. }
  4463. @override
  4464. void dispose() {
  4465. _tpController.dispose();
  4466. _slController.dispose();
  4467. super.dispose();
  4468. }
  4469. double get _entryPrice => widget.position.entryPrice;
  4470. double get _availableSize => widget.position.availableSize;
  4471. bool get _isLong => widget.position.side == OrderSide.long;
  4472. /// 预估盈利(止盈触发时)
  4473. double? _estimatedProfit() {
  4474. final tp = double.tryParse(_tpController.text);
  4475. if (tp == null || tp <= 0) return null;
  4476. return _isLong
  4477. ? (tp - _entryPrice) * _availableSize
  4478. : (_entryPrice - tp) * _availableSize;
  4479. }
  4480. /// 预估亏损(止损触发时)
  4481. double? _estimatedLoss() {
  4482. final sl = double.tryParse(_slController.text);
  4483. if (sl == null || sl <= 0) return null;
  4484. return _isLong
  4485. ? (sl - _entryPrice) * _availableSize
  4486. : (_entryPrice - sl) * _availableSize;
  4487. }
  4488. @override
  4489. Widget build(BuildContext context) {
  4490. final cs = Theme.of(context).colorScheme;
  4491. // 标记价格取仓位自身的 markPrice(仓位持有的币种),而非当前切换到的币对
  4492. final markPrice = widget.position.markPrice;
  4493. final coinPrecision = ref
  4494. .watch(futuresProvider(widget.symbol).select((s) => s.coinPrecision));
  4495. final pricePrecision = widget.pricePrecision;
  4496. final l10n = AppLocalizations.of(context)!;
  4497. final coinSymbol = _baseCoin(widget.position.symbol);
  4498. final isLong = _isLong;
  4499. final position = widget.position;
  4500. final sideLabel = isLong ? l10n.longHeadLabel : l10n.shortHeadLabel;
  4501. final leverageLabel = '${position.leverage.toInt()}X';
  4502. final coinName = coinSymbol;
  4503. final profit = _estimatedProfit();
  4504. final loss = _estimatedLoss();
  4505. return Padding(
  4506. padding: EdgeInsets.only(
  4507. bottom: MediaQuery.of(context).viewInsets.bottom + 24,
  4508. ),
  4509. child: Column(
  4510. mainAxisSize: MainAxisSize.min,
  4511. children: [
  4512. // ── 头部 ──
  4513. Row(
  4514. children: [
  4515. const SizedBox(width: 40),
  4516. Expanded(
  4517. child: Column(
  4518. children: [
  4519. const SizedBox(height: 16),
  4520. Text(l10n.takeProfitStopLoss,
  4521. style: TextStyle(
  4522. color: cs.onSurface,
  4523. fontSize: 16,
  4524. fontWeight: FontWeight.w600)),
  4525. const SizedBox(height: 2),
  4526. Text(
  4527. '${coinName}${l10n.perpetual} $sideLabel $leverageLabel ${_marginModeLabel(position.marginMode, l10n)}',
  4528. style: TextStyle(
  4529. color: cs.onSurface.withAlpha(153), fontSize: 12),
  4530. ),
  4531. const SizedBox(height: 4),
  4532. ],
  4533. ),
  4534. ),
  4535. SizedBox(
  4536. width: 40,
  4537. child: IconButton(
  4538. onPressed: () => Navigator.pop(context),
  4539. icon: Icon(Icons.close,
  4540. color: cs.onSurface.withAlpha(153), size: 20),
  4541. ),
  4542. ),
  4543. ],
  4544. ),
  4545. // ── 开仓均价 | 标记价格 ──
  4546. Padding(
  4547. padding: const EdgeInsets.fromLTRB(16, 4, 16, 12),
  4548. child: Row(
  4549. children: [
  4550. Expanded(
  4551. child: Column(
  4552. crossAxisAlignment: CrossAxisAlignment.start,
  4553. children: [
  4554. Text('${l10n.openAvgPrice}(USDT)',
  4555. style: TextStyle(
  4556. color: cs.onSurface.withAlpha(120),
  4557. fontSize: 11)),
  4558. const SizedBox(height: 2),
  4559. Text(formatPrice(_entryPrice),
  4560. style: TextStyle(
  4561. color: cs.onSurface,
  4562. fontSize: 14,
  4563. fontWeight: FontWeight.w600)),
  4564. ],
  4565. ),
  4566. ),
  4567. Expanded(
  4568. child: Column(
  4569. crossAxisAlignment: CrossAxisAlignment.end,
  4570. children: [
  4571. Text('${l10n.markLabel}(USDT)',
  4572. style: TextStyle(
  4573. color: cs.onSurface.withAlpha(120),
  4574. fontSize: 11)),
  4575. const SizedBox(height: 2),
  4576. Text(formatPrice(markPrice > 0 ? markPrice : _entryPrice),
  4577. style: TextStyle(
  4578. color: cs.onSurface,
  4579. fontSize: 14,
  4580. fontWeight: FontWeight.w600)),
  4581. ],
  4582. ),
  4583. ),
  4584. ],
  4585. ),
  4586. ),
  4587. // ── 复选框行 ──
  4588. Padding(
  4589. padding: const EdgeInsets.symmetric(horizontal: 16),
  4590. child: Row(
  4591. children: [
  4592. _TpslCheckbox(
  4593. label: l10n.setTakeProfit,
  4594. value: _tpEnabled,
  4595. onChanged: (v) => setState(() => _tpEnabled = v),
  4596. ),
  4597. const SizedBox(width: 24),
  4598. _TpslCheckbox(
  4599. label: l10n.setStopLoss,
  4600. value: _slEnabled,
  4601. onChanged: (v) => setState(() => _slEnabled = v),
  4602. ),
  4603. ],
  4604. ),
  4605. ),
  4606. const SizedBox(height: 14),
  4607. // ── 止盈输入 ──
  4608. if (_tpEnabled) ...[
  4609. _TpslInput(
  4610. controller: _tpController,
  4611. hint: l10n.tpTriggerPrice,
  4612. pricePrecision: pricePrecision,
  4613. onLatest: () {
  4614. final price = markPrice > 0 ? markPrice : _entryPrice;
  4615. final text = price.toStringAsFixed(pricePrecision);
  4616. _tpController.value = TextEditingValue(
  4617. text: text,
  4618. selection: TextSelection.collapsed(offset: text.length),
  4619. );
  4620. setState(() {});
  4621. },
  4622. onChanged: (_) => setState(() {}),
  4623. ),
  4624. const SizedBox(height: 10),
  4625. ],
  4626. // ── 止损输入 ──
  4627. if (_slEnabled) ...[
  4628. _TpslInput(
  4629. controller: _slController,
  4630. hint: l10n.slTriggerPrice,
  4631. pricePrecision: pricePrecision,
  4632. onLatest: () {
  4633. final price = markPrice > 0 ? markPrice : _entryPrice;
  4634. final text = price.toStringAsFixed(pricePrecision);
  4635. _slController.value = TextEditingValue(
  4636. text: text,
  4637. selection: TextSelection.collapsed(offset: text.length),
  4638. );
  4639. setState(() {});
  4640. },
  4641. onChanged: (_) => setState(() {}),
  4642. ),
  4643. const SizedBox(height: 10),
  4644. ],
  4645. // ── 数据行 ──
  4646. Padding(
  4647. padding: const EdgeInsets.fromLTRB(16, 6, 16, 4),
  4648. child: Column(
  4649. children: [
  4650. _TpslDataRow(
  4651. label: l10n.closeableSizeCoin(coinSymbol),
  4652. value: _availableSize > 0
  4653. ? formatAmount(_availableSize, decimals: coinPrecision)
  4654. : '--',
  4655. valueColor: cs.onSurface,
  4656. ),
  4657. const SizedBox(height: 8),
  4658. _TpslDataRow(
  4659. label: l10n.estProfit,
  4660. value: profit != null
  4661. ? '${profit >= 0 ? '+' : ''}${formatPrice(profit)}'
  4662. : '0.00',
  4663. valueColor: profit != null && profit >= 0
  4664. ? AppColors.rise
  4665. : AppColors.fall,
  4666. ),
  4667. const SizedBox(height: 8),
  4668. _TpslDataRow(
  4669. label: l10n.estLoss,
  4670. value: loss != null
  4671. ? '${loss >= 0 ? '+' : ''}${formatPrice(loss)}'
  4672. : '0.00',
  4673. valueColor: loss != null && loss < 0
  4674. ? AppColors.fall
  4675. : AppColors.rise,
  4676. ),
  4677. ],
  4678. ),
  4679. ),
  4680. const SizedBox(height: 16),
  4681. // ── 确定按钮 ──
  4682. Padding(
  4683. padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
  4684. child: SizedBox(
  4685. width: double.infinity,
  4686. height: 48,
  4687. child: ElevatedButton(
  4688. onPressed: () => _submit(context),
  4689. style: ElevatedButton.styleFrom(
  4690. backgroundColor: cs.inverseSurface,
  4691. elevation: 0,
  4692. shape: RoundedRectangleBorder(
  4693. borderRadius: BorderRadius.circular(8)),
  4694. ),
  4695. child: Text(l10n.confirmLabel,
  4696. style: TextStyle(
  4697. color: cs.onInverseSurface,
  4698. fontSize: 15,
  4699. fontWeight: FontWeight.w600)),
  4700. ),
  4701. ),
  4702. ),
  4703. ],
  4704. ),
  4705. );
  4706. }
  4707. Future<void> _submit(BuildContext context) async {
  4708. final tp = _tpEnabled ? double.tryParse(_tpController.text) : null;
  4709. final sl = _slEnabled ? double.tryParse(_slController.text) : null;
  4710. if (tp == null && sl == null) {
  4711. Navigator.pop(context);
  4712. return;
  4713. }
  4714. final err = await widget.notifier.setPositionTpsl(
  4715. widget.position,
  4716. profitPrice: tp,
  4717. lossPrice: sl,
  4718. );
  4719. if (!context.mounted) return;
  4720. Navigator.pop(context);
  4721. final l10n7 = AppLocalizations.of(context)!;
  4722. showTopToast(context,
  4723. message: resolveProviderError(err, l10n7) ?? l10n7.tpslSuccess,
  4724. backgroundColor: err != null ? AppColors.fall : AppColors.rise);
  4725. }
  4726. }
  4727. class _TpslCheckbox extends StatelessWidget {
  4728. const _TpslCheckbox(
  4729. {required this.label, required this.value, required this.onChanged});
  4730. final String label;
  4731. final bool value;
  4732. final ValueChanged<bool> onChanged;
  4733. @override
  4734. Widget build(BuildContext context) {
  4735. final cs = Theme.of(context).colorScheme;
  4736. final isDark = Theme.of(context).brightness == Brightness.dark;
  4737. return GestureDetector(
  4738. onTap: () => onChanged(!value),
  4739. child: Row(
  4740. mainAxisSize: MainAxisSize.min,
  4741. children: [
  4742. Container(
  4743. width: 16,
  4744. height: 16,
  4745. decoration: BoxDecoration(
  4746. color: value
  4747. ? AppColors.brand
  4748. : (isDark ? Colors.white : Colors.transparent),
  4749. borderRadius: BorderRadius.circular(3),
  4750. border: Border.all(
  4751. color: value ? AppColors.brand : cs.onSurface.withAlpha(220),
  4752. width: 1.5,
  4753. ),
  4754. ),
  4755. child: value
  4756. ? const Icon(Icons.check, size: 12, color: Colors.black)
  4757. : null,
  4758. ),
  4759. const SizedBox(width: 6),
  4760. Text(label, style: TextStyle(color: cs.onSurface, fontSize: 13)),
  4761. ],
  4762. ),
  4763. );
  4764. }
  4765. }
  4766. class _TpslInput extends StatefulWidget {
  4767. const _TpslInput({
  4768. required this.controller,
  4769. required this.hint,
  4770. required this.pricePrecision,
  4771. required this.onLatest,
  4772. required this.onChanged,
  4773. });
  4774. final TextEditingController controller;
  4775. final String hint;
  4776. final int pricePrecision;
  4777. final VoidCallback onLatest;
  4778. final ValueChanged<String> onChanged;
  4779. @override
  4780. State<_TpslInput> createState() => _TpslInputState();
  4781. }
  4782. class _TpslInputState extends State<_TpslInput> {
  4783. final _focusNode = FocusNode();
  4784. @override
  4785. void initState() {
  4786. super.initState();
  4787. _focusNode.addListener(() {
  4788. if (mounted) setState(() {});
  4789. });
  4790. }
  4791. @override
  4792. void dispose() {
  4793. _focusNode.dispose();
  4794. super.dispose();
  4795. }
  4796. @override
  4797. Widget build(BuildContext context) {
  4798. final cs = Theme.of(context).colorScheme;
  4799. final isDark = Theme.of(context).brightness == Brightness.dark;
  4800. final isFocused = _focusNode.hasFocus;
  4801. final bgColor = isFocused
  4802. ? (isDark ? AppColors.darkBgSecondary : Colors.white)
  4803. : (isDark ? AppColors.darkBgTertiary : AppColors.lightBgSecondary);
  4804. final activeBorder = isDark
  4805. ? AppColors.darkTextPrimary.withAlpha(200)
  4806. : const Color(0xFF383838);
  4807. return Padding(
  4808. padding: const EdgeInsets.symmetric(horizontal: 16),
  4809. child: Row(
  4810. children: [
  4811. Expanded(
  4812. child: Container(
  4813. height: 44,
  4814. decoration: BoxDecoration(
  4815. color: bgColor,
  4816. borderRadius: BorderRadius.circular(8),
  4817. border: Border.all(
  4818. color: isFocused ? activeBorder : cs.onSurface.withAlpha(40),
  4819. width: isFocused ? 1.5 : 1,
  4820. ),
  4821. ),
  4822. child: Row(
  4823. children: [
  4824. Padding(
  4825. padding: const EdgeInsets.only(left: 12),
  4826. child: Text(widget.hint,
  4827. style: TextStyle(
  4828. color: cs.onSurface.withAlpha(120), fontSize: 13)),
  4829. ),
  4830. Expanded(
  4831. child: TextField(
  4832. controller: widget.controller,
  4833. focusNode: _focusNode,
  4834. keyboardType:
  4835. const TextInputType.numberWithOptions(decimal: true),
  4836. inputFormatters: [
  4837. _PrecisionInputFormatter(widget.pricePrecision)
  4838. ],
  4839. onChanged: widget.onChanged,
  4840. textAlign: TextAlign.right,
  4841. decoration: InputDecoration(
  4842. border: InputBorder.none,
  4843. focusedBorder: InputBorder.none,
  4844. enabledBorder: InputBorder.none,
  4845. filled: false,
  4846. contentPadding:
  4847. const EdgeInsets.symmetric(horizontal: 8),
  4848. ),
  4849. style: TextStyle(
  4850. color: cs.onSurface,
  4851. fontSize: 13,
  4852. fontWeight: FontWeight.w600),
  4853. ),
  4854. ),
  4855. Padding(
  4856. padding: const EdgeInsets.only(right: 12),
  4857. child: Text('USDT',
  4858. style: TextStyle(
  4859. color: cs.onSurface.withAlpha(120), fontSize: 12)),
  4860. ),
  4861. ],
  4862. ),
  4863. ),
  4864. ),
  4865. const SizedBox(width: 8),
  4866. GestureDetector(
  4867. onTap: widget.onLatest,
  4868. child: Container(
  4869. height: 44,
  4870. padding: const EdgeInsets.symmetric(horizontal: 12),
  4871. decoration: BoxDecoration(
  4872. color: cs.inverseSurface,
  4873. borderRadius: BorderRadius.circular(8),
  4874. ),
  4875. alignment: Alignment.center,
  4876. child: Text(AppLocalizations.of(context)!.latestLabel,
  4877. style: TextStyle(
  4878. color: cs.onInverseSurface,
  4879. fontSize: 13,
  4880. fontWeight: FontWeight.w500)),
  4881. ),
  4882. ),
  4883. ],
  4884. ),
  4885. );
  4886. }
  4887. }
  4888. class _TpslDataRow extends StatelessWidget {
  4889. const _TpslDataRow(
  4890. {required this.label, required this.value, required this.valueColor});
  4891. final String label;
  4892. final String value;
  4893. final Color valueColor;
  4894. @override
  4895. Widget build(BuildContext context) {
  4896. final cs = Theme.of(context).colorScheme;
  4897. return Row(
  4898. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  4899. children: [
  4900. Text(label,
  4901. style: TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 12)),
  4902. Text(value,
  4903. style: TextStyle(
  4904. color: valueColor, fontSize: 12, fontWeight: FontWeight.w500)),
  4905. ],
  4906. );
  4907. }
  4908. }
  4909. class _ClosePositionSheet extends ConsumerStatefulWidget {
  4910. const _ClosePositionSheet(
  4911. {required this.position, required this.notifier, required this.symbol});
  4912. final FuturesPosition position;
  4913. final FuturesNotifier notifier;
  4914. final String symbol;
  4915. @override
  4916. ConsumerState<_ClosePositionSheet> createState() =>
  4917. _ClosePositionSheetState();
  4918. }
  4919. class _ClosePositionSheetState extends ConsumerState<_ClosePositionSheet> {
  4920. final _priceController = TextEditingController();
  4921. final _volumeController = TextEditingController();
  4922. final _priceFocusNode = FocusNode();
  4923. final _volumeFocusNode = FocusNode();
  4924. bool _isMarket = false; // false=限价, true=市价
  4925. double _percent = 0;
  4926. String _baseCoin(String sym) {
  4927. if (sym.contains('/')) return sym.split('/').first;
  4928. return sym.toUpperCase().replaceFirst(RegExp(r'USDT$'), '');
  4929. }
  4930. @override
  4931. void initState() {
  4932. super.initState();
  4933. _priceFocusNode.addListener(() {
  4934. if (mounted) setState(() {});
  4935. });
  4936. _volumeFocusNode.addListener(() {
  4937. if (mounted) setState(() {});
  4938. });
  4939. }
  4940. @override
  4941. void dispose() {
  4942. _priceController.dispose();
  4943. _volumeController.dispose();
  4944. _priceFocusNode.dispose();
  4945. _volumeFocusNode.dispose();
  4946. super.dispose();
  4947. }
  4948. void _onPercentChanged(double p) {
  4949. setState(() => _percent = p);
  4950. final avail = widget.position.availableSize;
  4951. final vol = avail * p;
  4952. if (vol <= 0) {
  4953. _volumeController.clear();
  4954. } else {
  4955. final precision = ref
  4956. .read(futuresProvider(widget.symbol).select((s) => s.coinPrecision));
  4957. _volumeController.text = vol.toStringAsFixed(precision);
  4958. }
  4959. }
  4960. void _syncPercentFromVolume() {
  4961. final avail = widget.position.availableSize;
  4962. if (avail <= 0) return;
  4963. final vol =
  4964. double.tryParse(_volumeController.text.replaceAll(',', '')) ?? 0;
  4965. setState(() => _percent = (vol / avail).clamp(0.0, 1.0));
  4966. }
  4967. @override
  4968. Widget build(BuildContext context) {
  4969. final cs = Theme.of(context).colorScheme;
  4970. final isDark = Theme.of(context).brightness == Brightness.dark;
  4971. final inputUnfocusedBg =
  4972. isDark ? AppColors.darkBgTertiary : AppColors.lightBgSecondary;
  4973. final inputFocusedBg = isDark ? AppColors.darkBgSecondary : Colors.white;
  4974. final inputActiveBorder = isDark
  4975. ? AppColors.darkTextPrimary.withAlpha(200)
  4976. : const Color(0xFF383838);
  4977. final coinPrecision = ref
  4978. .watch(futuresProvider(widget.symbol).select((s) => s.coinPrecision));
  4979. final pricePrecision = ref
  4980. .watch(futuresProvider(widget.symbol).select((s) => s.pricePrecision));
  4981. final pos = widget.position;
  4982. final l10n = AppLocalizations.of(context)!;
  4983. final isLong = pos.side == OrderSide.long;
  4984. final sideLabel = isLong ? l10n.longHeadLabel : l10n.shortHeadLabel;
  4985. final leverage = pos.leverage.toInt();
  4986. final availSize = pos.availableSize;
  4987. final coinSymbol = _baseCoin(pos.symbol);
  4988. // 预计盈亏:限价用输入价格,市价用标记价格估算
  4989. double? estPnl;
  4990. final closeVol =
  4991. double.tryParse(_volumeController.text.replaceAll(',', '')) ?? 0;
  4992. if (closeVol > 0) {
  4993. if (_isMarket) {
  4994. // 市价:以标记价格估算盈亏
  4995. final diff = isLong
  4996. ? (pos.markPrice - pos.entryPrice)
  4997. : (pos.entryPrice - pos.markPrice);
  4998. estPnl = diff * closeVol;
  4999. } else {
  5000. final price = double.tryParse(_priceController.text);
  5001. if (price != null && price > 0) {
  5002. // 多头平仓:卖出价 - 开仓价;空头平仓:开仓价 - 买入价
  5003. final diff =
  5004. isLong ? (price - pos.entryPrice) : (pos.entryPrice - price);
  5005. estPnl = diff * closeVol;
  5006. }
  5007. }
  5008. }
  5009. return Padding(
  5010. padding: EdgeInsets.only(
  5011. left: 16,
  5012. right: 16,
  5013. top: 20,
  5014. bottom: MediaQuery.of(context).viewInsets.bottom + 24,
  5015. ),
  5016. child: Column(
  5017. mainAxisSize: MainAxisSize.min,
  5018. children: [
  5019. // ── 标题行 ────────────────────────────────────────────
  5020. SizedBox(
  5021. width: double.infinity,
  5022. child: Stack(
  5023. alignment: Alignment.center,
  5024. children: [
  5025. Text(l10n.closePositionBtn,
  5026. style: TextStyle(
  5027. color: cs.onSurface,
  5028. fontSize: 16,
  5029. fontWeight: FontWeight.w600)),
  5030. Positioned(
  5031. right: 0,
  5032. child: GestureDetector(
  5033. onTap: () => Navigator.pop(context),
  5034. child: Icon(Icons.close,
  5035. size: 20, color: cs.onSurface.withAlpha(153)),
  5036. ),
  5037. ),
  5038. ],
  5039. ),
  5040. ),
  5041. const SizedBox(height: 4),
  5042. Text(
  5043. '${pos.symbol} ${l10n.perpetual} $sideLabel ${leverage}X ${_marginModeLabel(pos.marginMode, l10n)}',
  5044. style: TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 12),
  5045. ),
  5046. const SizedBox(height: 16),
  5047. // ── 开仓均价 / 标记价格(带边框盒子,对应原型设计)────
  5048. Row(
  5049. children: [
  5050. Expanded(
  5051. child: Column(
  5052. crossAxisAlignment: CrossAxisAlignment.start,
  5053. children: [
  5054. Text('${l10n.openAvgPrice}(USDT)',
  5055. style: TextStyle(
  5056. color: cs.onSurface.withAlpha(153), fontSize: 11)),
  5057. const SizedBox(height: 2),
  5058. Text(formatAmount(pos.entryPrice),
  5059. style: TextStyle(
  5060. color: cs.onSurface,
  5061. fontSize: 14,
  5062. fontWeight: FontWeight.w500)),
  5063. ],
  5064. ),
  5065. ),
  5066. Column(
  5067. crossAxisAlignment: CrossAxisAlignment.end,
  5068. children: [
  5069. Text('${l10n.markLabel}(USDT)',
  5070. style: TextStyle(
  5071. color: cs.onSurface.withAlpha(153), fontSize: 11)),
  5072. const SizedBox(height: 2),
  5073. GestureDetector(
  5074. onTap: _isMarket
  5075. ? null
  5076. : () {
  5077. final text =
  5078. pos.markPrice.toStringAsFixed(pricePrecision);
  5079. _priceController.value = TextEditingValue(
  5080. text: text,
  5081. selection:
  5082. TextSelection.collapsed(offset: text.length),
  5083. );
  5084. setState(() {});
  5085. },
  5086. child: Text(formatAmount(pos.markPrice),
  5087. style: TextStyle(
  5088. color: cs.onSurface,
  5089. fontSize: 14,
  5090. fontWeight: FontWeight.w500)),
  5091. ),
  5092. ],
  5093. ),
  5094. ],
  5095. ),
  5096. const SizedBox(height: 12),
  5097. // ── 价格输入 + 限价/市价切换 ─────────────────────────
  5098. Row(
  5099. children: [
  5100. Expanded(
  5101. child: Container(
  5102. height: 46,
  5103. decoration: BoxDecoration(
  5104. color: _isMarket
  5105. ? inputUnfocusedBg
  5106. : (_priceFocusNode.hasFocus
  5107. ? inputFocusedBg
  5108. : inputUnfocusedBg),
  5109. borderRadius: BorderRadius.circular(8),
  5110. border: !_isMarket && _priceFocusNode.hasFocus
  5111. ? Border.all(color: inputActiveBorder, width: 1.5)
  5112. : Border.all(
  5113. color: cs.onSurface.withAlpha(40), width: 1),
  5114. ),
  5115. child: TextField(
  5116. controller: _priceController,
  5117. focusNode: _priceFocusNode,
  5118. enabled: !_isMarket,
  5119. keyboardType:
  5120. const TextInputType.numberWithOptions(decimal: true),
  5121. inputFormatters: [_PrecisionInputFormatter(pricePrecision)],
  5122. style: TextStyle(color: cs.onSurface, fontSize: 14),
  5123. onChanged: (_) => setState(() {}),
  5124. decoration: InputDecoration(
  5125. hintText:
  5126. _isMarket ? l10n.marketHint : l10n.pricePlaceholder,
  5127. hintStyle: TextStyle(
  5128. color: cs.onSurface.withAlpha(100), fontSize: 14),
  5129. suffixText: 'USDT',
  5130. suffixStyle: TextStyle(
  5131. color: cs.onSurface.withAlpha(100), fontSize: 12),
  5132. filled: false,
  5133. contentPadding:
  5134. const EdgeInsets.symmetric(horizontal: 12),
  5135. border: InputBorder.none,
  5136. focusedBorder: InputBorder.none,
  5137. enabledBorder: InputBorder.none,
  5138. disabledBorder: InputBorder.none,
  5139. ),
  5140. ),
  5141. ),
  5142. ),
  5143. const SizedBox(width: 8),
  5144. GestureDetector(
  5145. onTap: () => setState(() {
  5146. _isMarket = !_isMarket;
  5147. _priceController.clear();
  5148. }),
  5149. child: Container(
  5150. height: 46,
  5151. padding: const EdgeInsets.symmetric(horizontal: 16),
  5152. decoration: BoxDecoration(
  5153. color: AppColors.brand,
  5154. borderRadius: BorderRadius.circular(8),
  5155. ),
  5156. alignment: Alignment.center,
  5157. child: Text(
  5158. _isMarket ? l10n.marketHint : l10n.limitLabel,
  5159. style: TextStyle(
  5160. color: Colors.black,
  5161. fontSize: 14,
  5162. fontWeight: FontWeight.w600,
  5163. ),
  5164. ),
  5165. ),
  5166. ),
  5167. ],
  5168. ),
  5169. if (!_isMarket) ...[
  5170. const SizedBox(height: 4),
  5171. Align(
  5172. alignment: Alignment.centerLeft,
  5173. child: Text(
  5174. isLong ? l10n.closePositionMsgLong : l10n.closePositionMsgShort,
  5175. style:
  5176. TextStyle(color: cs.onSurface.withAlpha(100), fontSize: 11),
  5177. ),
  5178. ),
  5179. ],
  5180. const SizedBox(height: 8),
  5181. // ── 平仓数量输入(带币种后缀)────────────────────────
  5182. Container(
  5183. height: 46,
  5184. decoration: BoxDecoration(
  5185. color:
  5186. _volumeFocusNode.hasFocus ? inputFocusedBg : inputUnfocusedBg,
  5187. borderRadius: BorderRadius.circular(8),
  5188. border: _volumeFocusNode.hasFocus
  5189. ? Border.all(color: inputActiveBorder, width: 1.5)
  5190. : Border.all(color: cs.onSurface.withAlpha(40), width: 1),
  5191. ),
  5192. child: TextField(
  5193. controller: _volumeController,
  5194. focusNode: _volumeFocusNode,
  5195. keyboardType:
  5196. const TextInputType.numberWithOptions(decimal: true),
  5197. inputFormatters: [_PrecisionInputFormatter(coinPrecision)],
  5198. style: TextStyle(color: cs.onSurface, fontSize: 14),
  5199. onChanged: (_) => _syncPercentFromVolume(),
  5200. decoration: InputDecoration(
  5201. hintText: l10n.enterCloseVolume,
  5202. hintStyle:
  5203. TextStyle(color: cs.onSurface.withAlpha(100), fontSize: 14),
  5204. suffixText: coinSymbol,
  5205. suffixStyle:
  5206. TextStyle(color: cs.onSurface.withAlpha(100), fontSize: 12),
  5207. filled: false,
  5208. contentPadding: const EdgeInsets.symmetric(horizontal: 12),
  5209. border: InputBorder.none,
  5210. focusedBorder: InputBorder.none,
  5211. enabledBorder: InputBorder.none,
  5212. ),
  5213. ),
  5214. ),
  5215. const SizedBox(height: 12),
  5216. // ── 滑动条 ──────────────────────────────────────────
  5217. _PercentSlider(
  5218. percent: _percent,
  5219. onChanged: _onPercentChanged,
  5220. ),
  5221. const SizedBox(height: 12),
  5222. // ── 可平量 / 预计盈亏 ─────────────────────────────────
  5223. Row(
  5224. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  5225. children: [
  5226. Text(l10n.closeableSizeCoin(coinSymbol),
  5227. style: TextStyle(
  5228. color: cs.onSurface.withAlpha(153), fontSize: 12)),
  5229. Text(formatAmount(availSize, decimals: coinPrecision),
  5230. style: TextStyle(color: cs.onSurface, fontSize: 12)),
  5231. ],
  5232. ),
  5233. const SizedBox(height: 6),
  5234. Row(
  5235. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  5236. children: [
  5237. Text(l10n.estPnlLabel,
  5238. style: TextStyle(
  5239. color: cs.onSurface.withAlpha(153), fontSize: 12)),
  5240. Text(
  5241. estPnl == null
  5242. ? '-- USDT'
  5243. : '${estPnl >= 0 ? '+' : ''}${formatAmount(estPnl)} USDT',
  5244. style: TextStyle(
  5245. color: estPnl == null
  5246. ? cs.onSurface.withAlpha(153)
  5247. : (estPnl >= 0 ? AppColors.rise : AppColors.fall),
  5248. fontSize: 12,
  5249. fontWeight: FontWeight.w500,
  5250. ),
  5251. ),
  5252. ],
  5253. ),
  5254. const SizedBox(height: 16),
  5255. // ── 确定按钮 ──────────────────────────────────────────
  5256. SizedBox(
  5257. width: double.infinity,
  5258. height: 52,
  5259. child: ElevatedButton(
  5260. onPressed: () => _close(context),
  5261. style: ElevatedButton.styleFrom(
  5262. backgroundColor: AppColors.brand,
  5263. elevation: 0,
  5264. shape: RoundedRectangleBorder(
  5265. borderRadius: BorderRadius.circular(26),
  5266. ),
  5267. ),
  5268. child: Text(
  5269. l10n.confirmLabel,
  5270. style: TextStyle(
  5271. color: Colors.black,
  5272. fontSize: 16,
  5273. fontWeight: FontWeight.w600),
  5274. ),
  5275. ),
  5276. ),
  5277. ],
  5278. ),
  5279. );
  5280. }
  5281. Future<void> _close(BuildContext context) async {
  5282. final volume = double.tryParse(_volumeController.text.replaceAll(',', ''));
  5283. // 数量为空或0不允许提交
  5284. if (volume == null || volume <= 0) {
  5285. showTopToast(context,
  5286. message: AppLocalizations.of(context)!.enterCloseVolume,
  5287. backgroundColor: AppColors.fall);
  5288. return;
  5289. }
  5290. String? err;
  5291. if (_isMarket) {
  5292. err = await widget.notifier.closeMarket(widget.position, volume: volume);
  5293. } else {
  5294. final price = double.tryParse(_priceController.text) ?? 0;
  5295. // 限价单必须输入价格,未填则提示且不关闭弹窗
  5296. if (price <= 0) {
  5297. showTopToast(context,
  5298. message: AppLocalizations.of(context)!.enterLimitPrice,
  5299. backgroundColor: AppColors.fall);
  5300. return;
  5301. }
  5302. err = await widget.notifier
  5303. .closeLimit(widget.position, price, volume: volume);
  5304. }
  5305. if (!context.mounted) return;
  5306. final l10n8 = AppLocalizations.of(context)!;
  5307. if (err != null) {
  5308. showTopToast(context,
  5309. message: resolveProviderError(err, l10n8) ?? err,
  5310. backgroundColor: AppColors.fall);
  5311. return;
  5312. }
  5313. Navigator.pop(context);
  5314. showTopToast(context,
  5315. message: l10n8.closeOrderSubmitted, backgroundColor: AppColors.rise);
  5316. }
  5317. }
  5318. class _AssetsPanel extends StatelessWidget {
  5319. const _AssetsPanel({required this.info});
  5320. final FuturesAccountInfo info;
  5321. @override
  5322. Widget build(BuildContext context) {
  5323. final cs = Theme.of(context).colorScheme;
  5324. return Padding(
  5325. padding: const EdgeInsets.fromLTRB(24, 12, 24, 12),
  5326. child: Column(
  5327. crossAxisAlignment: CrossAxisAlignment.start,
  5328. children: [
  5329. Text(AppLocalizations.of(context)!.contractAccountUsdt,
  5330. style:
  5331. TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 12)),
  5332. const SizedBox(height: 4),
  5333. Text(
  5334. formatAmount(info.totalBalance),
  5335. style: TextStyle(
  5336. color: cs.onSurface,
  5337. fontSize: 22,
  5338. fontWeight: FontWeight.w700,
  5339. ),
  5340. ),
  5341. const SizedBox(height: 10),
  5342. Row(
  5343. children: [
  5344. _AssetItem(
  5345. label: AppLocalizations.of(context)!.availableMargin,
  5346. value: formatAmount(info.availableMargin),
  5347. align: CrossAxisAlignment.start),
  5348. _AssetItem(
  5349. label: AppLocalizations.of(context)!.usedMargin,
  5350. value: formatAmount(info.usedMargin),
  5351. align: CrossAxisAlignment.center),
  5352. _AssetItem(
  5353. label: AppLocalizations.of(context)!.unrealizedPnl,
  5354. value:
  5355. '${info.unrealizedPnl >= 0 ? '+' : ''}${formatAmount(info.unrealizedPnl)}',
  5356. valueColor:
  5357. info.unrealizedPnl >= 0 ? AppColors.rise : AppColors.fall,
  5358. align: CrossAxisAlignment.end,
  5359. ),
  5360. ],
  5361. ),
  5362. ],
  5363. ),
  5364. );
  5365. }
  5366. }
  5367. class _AssetItem extends StatelessWidget {
  5368. const _AssetItem({
  5369. required this.label,
  5370. required this.value,
  5371. this.valueColor,
  5372. this.align = CrossAxisAlignment.start,
  5373. });
  5374. final String label;
  5375. final String value;
  5376. final Color? valueColor;
  5377. final CrossAxisAlignment align;
  5378. @override
  5379. Widget build(BuildContext context) {
  5380. final cs = Theme.of(context).colorScheme;
  5381. final textAlign = align == CrossAxisAlignment.end
  5382. ? TextAlign.right
  5383. : align == CrossAxisAlignment.center
  5384. ? TextAlign.center
  5385. : TextAlign.left;
  5386. return Expanded(
  5387. child: Column(
  5388. crossAxisAlignment: align,
  5389. children: [
  5390. Text(label,
  5391. textAlign: textAlign,
  5392. style:
  5393. TextStyle(color: cs.onSurface.withAlpha(153), fontSize: 10)),
  5394. const SizedBox(height: 2),
  5395. Text(value,
  5396. textAlign: textAlign,
  5397. style: TextStyle(
  5398. color: valueColor ?? cs.onSurface,
  5399. fontSize: 13,
  5400. fontWeight: FontWeight.w500)),
  5401. ],
  5402. ),
  5403. );
  5404. }
  5405. }
  5406. double _toDouble(dynamic v) {
  5407. if (v == null) return 0.0;
  5408. if (v is num) return v.toDouble();
  5409. return double.tryParse(v.toString()) ?? 0.0;
  5410. }
  5411. /// AppBar 顶部"现货 / 永续合约"切换 Tab
  5412. /// 与 spot_screen.dart 中的 _SegmentedTabHeader 保持一致样式
  5413. class _SpotFuturesTabHeader extends StatelessWidget {
  5414. const _SpotFuturesTabHeader({required this.activeIndex, required this.onTap});
  5415. final int activeIndex; // 0=现货 1=合约
  5416. final ValueChanged<int> onTap;
  5417. @override
  5418. Widget build(BuildContext context) {
  5419. final cs = Theme.of(context).colorScheme;
  5420. final l10n = AppLocalizations.of(context)!;
  5421. final items = [l10n.spotTab, l10n.perpetualContract];
  5422. return Row(
  5423. mainAxisSize: MainAxisSize.min,
  5424. children: List.generate(items.length, (i) {
  5425. final isActive = i == activeIndex;
  5426. return Padding(
  5427. padding: EdgeInsets.only(right: i == 0 ? 16 : 0),
  5428. child: GestureDetector(
  5429. behavior: HitTestBehavior.opaque,
  5430. onTap: () => onTap(i),
  5431. child: Column(
  5432. mainAxisSize: MainAxisSize.min,
  5433. children: [
  5434. Text(
  5435. items[i],
  5436. style: TextStyle(
  5437. color:
  5438. isActive ? cs.onSurface : cs.onSurface.withAlpha(140),
  5439. fontSize: 16,
  5440. fontWeight: isActive ? FontWeight.w700 : FontWeight.w500,
  5441. ),
  5442. ),
  5443. const SizedBox(height: 4),
  5444. Container(
  5445. width: 28,
  5446. height: 3,
  5447. color: isActive ? AppColors.brand : Colors.transparent,
  5448. ),
  5449. ],
  5450. ),
  5451. ),
  5452. );
  5453. }),
  5454. );
  5455. }
  5456. }
  5457. /// 精度输入格式化器
  5458. /// [decimals] = 0 时只允许正整数;> 0 时允许最多 [decimals] 位小数
  5459. class _PrecisionInputFormatter extends TextInputFormatter {
  5460. const _PrecisionInputFormatter(this.decimals);
  5461. final int decimals;
  5462. @override
  5463. TextEditingValue formatEditUpdate(
  5464. TextEditingValue oldValue, TextEditingValue newValue) {
  5465. final text = newValue.text;
  5466. if (text.isEmpty) return newValue;
  5467. if (decimals == 0) {
  5468. // 只允许正整数
  5469. if (!RegExp(r'^\d+$').hasMatch(text)) return oldValue;
  5470. return newValue;
  5471. }
  5472. // 允许小数:最多 [decimals] 位
  5473. final pattern = RegExp(r'^\d+\.?\d{0,' + decimals.toString() + r'}$');
  5474. if (!pattern.hasMatch(text)) return oldValue;
  5475. // 不允许以多个小数点开头
  5476. if (text.indexOf('.') != text.lastIndexOf('.')) return oldValue;
  5477. return newValue;
  5478. }
  5479. }
  5480. // ══════════════════════════════════════════════════════════════════════════════
  5481. // 仓位分享相关 widget
  5482. // ══════════════════════════════════════════════════════════════════════════════
  5483. /// 分享底部弹窗:预览分享卡片 + 操作按钮(供资产页复用)
  5484. class SharePositionSheet extends ConsumerStatefulWidget {
  5485. const SharePositionSheet({super.key, required this.position});
  5486. final FuturesPosition position;
  5487. @override
  5488. ConsumerState<SharePositionSheet> createState() => _SharePositionSheetState();
  5489. }
  5490. class _SharePositionSheetState extends ConsumerState<SharePositionSheet> {
  5491. final _cardKey = GlobalKey();
  5492. bool _sharing = false;
  5493. bool _saving = false;
  5494. String? _inviteCode;
  5495. String? _inviteUrl;
  5496. @override
  5497. void initState() {
  5498. super.initState();
  5499. _loadInviteInfo();
  5500. }
  5501. Future<void> _loadInviteInfo() async {
  5502. try {
  5503. final dio = ref.read(dioClientProvider);
  5504. final data = await AuthService(dio).getMyInfo();
  5505. final prefix = data['promotionPrefix']?.toString() ?? '';
  5506. final code = data['promotionCode']?.toString() ?? '';
  5507. final url =
  5508. (prefix.isNotEmpty || code.isNotEmpty) ? '$prefix$code' : null;
  5509. if (mounted) {
  5510. setState(() {
  5511. _inviteCode = code.isNotEmpty ? code : null;
  5512. _inviteUrl = url;
  5513. });
  5514. }
  5515. } catch (e) {
  5516. print('[ShareCard] _loadInviteInfo error: $e');
  5517. }
  5518. }
  5519. @override
  5520. Widget build(BuildContext context) {
  5521. final cs = Theme.of(context).colorScheme;
  5522. final isDark = Theme.of(context).brightness == Brightness.dark;
  5523. final pos = widget.position;
  5524. final pnlPositive = pos.unrealizedPnl >= 0;
  5525. final l10n = AppLocalizations.of(context)!;
  5526. return Container(
  5527. decoration: BoxDecoration(
  5528. color: isDark ? AppColors.darkBgSecondary : AppColors.lightBgSecondary,
  5529. borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
  5530. ),
  5531. padding: const EdgeInsets.fromLTRB(16, 16, 16, 32),
  5532. child: Column(
  5533. mainAxisSize: MainAxisSize.min,
  5534. children: [
  5535. // 拖拽指示条
  5536. Container(
  5537. width: 36,
  5538. height: 4,
  5539. decoration: BoxDecoration(
  5540. color: cs.onSurface.withAlpha(60),
  5541. borderRadius: BorderRadius.circular(2),
  5542. ),
  5543. ),
  5544. const SizedBox(height: 16),
  5545. // 分享卡片预览
  5546. RepaintBoundary(
  5547. key: _cardKey,
  5548. child: _PositionShareCard(
  5549. position: pos,
  5550. inviteCode: _inviteCode,
  5551. inviteUrl: _inviteUrl,
  5552. ),
  5553. ),
  5554. const SizedBox(height: 24),
  5555. // 操作按钮行:取消 | 保存海报 | 分享
  5556. Row(
  5557. children: [
  5558. Expanded(
  5559. child: OutlinedButton(
  5560. onPressed: () => Navigator.of(context).pop(),
  5561. style: OutlinedButton.styleFrom(
  5562. padding: const EdgeInsets.symmetric(vertical: 12),
  5563. shape: RoundedRectangleBorder(
  5564. borderRadius: BorderRadius.circular(8)),
  5565. ),
  5566. child: Text(l10n.cancelLabel,
  5567. style: TextStyle(color: cs.onSurface, fontSize: 14)),
  5568. ),
  5569. ),
  5570. const SizedBox(width: 8),
  5571. Expanded(
  5572. child: OutlinedButton(
  5573. onPressed: _saving ? null : () => _doSave(context),
  5574. style: OutlinedButton.styleFrom(
  5575. padding: const EdgeInsets.symmetric(vertical: 12),
  5576. shape: RoundedRectangleBorder(
  5577. borderRadius: BorderRadius.circular(8)),
  5578. ),
  5579. child: _saving
  5580. ? SizedBox(
  5581. width: 16,
  5582. height: 16,
  5583. child: CircularProgressIndicator(
  5584. strokeWidth: 2,
  5585. color: cs.onSurface.withAlpha(153)),
  5586. )
  5587. : Text(l10n.savePoster,
  5588. style: TextStyle(color: cs.onSurface, fontSize: 14)),
  5589. ),
  5590. ),
  5591. const SizedBox(width: 8),
  5592. Expanded(
  5593. child: ElevatedButton(
  5594. onPressed: _sharing ? null : () => _doShare(context),
  5595. style: ElevatedButton.styleFrom(
  5596. backgroundColor:
  5597. pnlPositive ? AppColors.rise : AppColors.fall,
  5598. padding: const EdgeInsets.symmetric(vertical: 12),
  5599. shape: RoundedRectangleBorder(
  5600. borderRadius: BorderRadius.circular(8)),
  5601. elevation: 0,
  5602. ),
  5603. child: _sharing
  5604. ? const SizedBox(
  5605. width: 16,
  5606. height: 16,
  5607. child: CircularProgressIndicator(
  5608. strokeWidth: 2, color: Colors.white),
  5609. )
  5610. : Text(l10n.shareLabel,
  5611. style: const TextStyle(
  5612. color: Colors.white,
  5613. fontSize: 14,
  5614. fontWeight: FontWeight.w600)),
  5615. ),
  5616. ),
  5617. ],
  5618. ),
  5619. ],
  5620. ),
  5621. );
  5622. }
  5623. Future<Uint8List?> _renderCard() async {
  5624. final boundary =
  5625. _cardKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
  5626. if (boundary == null) return null;
  5627. final image = await boundary.toImage(pixelRatio: 3.0);
  5628. final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
  5629. return byteData?.buffer.asUint8List();
  5630. }
  5631. Future<void> _doSave(BuildContext context) async {
  5632. setState(() => _saving = true);
  5633. try {
  5634. final bytes = await _renderCard();
  5635. if (bytes == null) return;
  5636. // 申请权限(首次弹系统弹窗;已拒绝则 false,但仍尝试写入让 GalException 决定)
  5637. await Gal.requestAccess();
  5638. await Gal.putImageBytes(
  5639. bytes,
  5640. name: 'position_share_${DateTime.now().millisecondsSinceEpoch}',
  5641. );
  5642. if (!context.mounted) return;
  5643. showTopToast(context,
  5644. message: AppLocalizations.of(context)!.saveSuccess,
  5645. backgroundColor: AppColors.rise);
  5646. } on GalException catch (e) {
  5647. if (!context.mounted) return;
  5648. // accessDenied 时引导用户去设置开启权限
  5649. final l10n = AppLocalizations.of(context)!;
  5650. if (e.type == GalExceptionType.accessDenied) {
  5651. showTopToast(context,
  5652. message: l10n.photoPermissionDenied,
  5653. backgroundColor: AppColors.fall);
  5654. } else {
  5655. showTopToast(context,
  5656. message: l10n.saveFailed, backgroundColor: AppColors.fall);
  5657. }
  5658. } catch (e) {
  5659. if (context.mounted) {
  5660. showTopToast(context,
  5661. message: AppLocalizations.of(context)!.saveFailed,
  5662. backgroundColor: AppColors.fall);
  5663. }
  5664. } finally {
  5665. if (mounted) setState(() => _saving = false);
  5666. }
  5667. }
  5668. Future<void> _doShare(BuildContext context) async {
  5669. setState(() => _sharing = true);
  5670. try {
  5671. final bytes = await _renderCard();
  5672. if (bytes == null) return;
  5673. final tmpDir = await getTemporaryDirectory();
  5674. final file = File(
  5675. '${tmpDir.path}/position_share_${DateTime.now().millisecondsSinceEpoch}.png');
  5676. await file.writeAsBytes(bytes);
  5677. if (!context.mounted) return;
  5678. Navigator.of(context).pop();
  5679. await Share.shareXFiles(
  5680. [XFile(file.path, mimeType: 'image/png')],
  5681. subject: AppLocalizations.of(context)!.myFuturesPosition,
  5682. );
  5683. } catch (e) {
  5684. if (context.mounted) {
  5685. showTopToast(context,
  5686. message: AppLocalizations.of(context)!.shareFailed,
  5687. backgroundColor: AppColors.fall);
  5688. }
  5689. } finally {
  5690. if (mounted) setState(() => _sharing = false);
  5691. }
  5692. }
  5693. }
  5694. /// 分享卡片内容
  5695. class _PositionShareCard extends StatelessWidget {
  5696. const _PositionShareCard({
  5697. required this.position,
  5698. this.inviteCode,
  5699. this.inviteUrl,
  5700. });
  5701. final FuturesPosition position;
  5702. final String? inviteCode;
  5703. final String? inviteUrl;
  5704. String _baseCoin(String sym) {
  5705. if (sym.contains('/')) return sym.split('/').first;
  5706. return sym.toUpperCase().replaceFirst(RegExp(r'USDT$'), '');
  5707. }
  5708. String _formatNow() {
  5709. final t = DateTime.now();
  5710. final mo = t.month.toString().padLeft(2, '0');
  5711. final d = t.day.toString().padLeft(2, '0');
  5712. final h = t.hour.toString().padLeft(2, '0');
  5713. final mi = t.minute.toString().padLeft(2, '0');
  5714. final s = t.second.toString().padLeft(2, '0');
  5715. return '${t.year}-$mo-$d $h:$mi:$s';
  5716. }
  5717. @override
  5718. Widget build(BuildContext context) {
  5719. final isDark = Theme.of(context).brightness == Brightness.dark;
  5720. final pos = position;
  5721. final isLong = pos.side == OrderSide.long;
  5722. final sideColor = isLong ? AppColors.rise : AppColors.fall;
  5723. final pnlPositive = pos.unrealizedPnl >= 0;
  5724. final pnlColor = pnlPositive ? AppColors.rise : AppColors.fall;
  5725. final coinSymbol = _baseCoin(pos.symbol);
  5726. final roeStr = '${pnlPositive ? '+' : ''}${formatAmount(pos.roe)}%';
  5727. final qrData = inviteUrl;
  5728. // 主题色变量
  5729. final bgColors = isDark
  5730. ? const [Color(0xFF1A1F2E), Color(0xFF0D1117)]
  5731. : const [Color(0xFFF8F9FB), Color(0xFFEEF0F3)];
  5732. final textPrimary = isDark ? Colors.white : const Color(0xFF1A1F2E);
  5733. final textSecondary = isDark
  5734. ? Colors.white.withAlpha(120)
  5735. : const Color(0xFF1A1F2E).withAlpha(120);
  5736. final textMuted = isDark
  5737. ? Colors.white.withAlpha(80)
  5738. : const Color(0xFF1A1F2E).withAlpha(80);
  5739. final borderColor = isDark
  5740. ? Colors.white.withAlpha(40)
  5741. : const Color(0xFF1A1F2E).withAlpha(30);
  5742. final qrFgColor = isDark ? Colors.white : Colors.black;
  5743. final qrBgColor = isDark ? const Color(0xFF1A1F2E) : Colors.white;
  5744. return Container(
  5745. width: double.infinity,
  5746. decoration: BoxDecoration(
  5747. gradient: LinearGradient(
  5748. begin: Alignment.topLeft,
  5749. end: Alignment.bottomRight,
  5750. colors: bgColors,
  5751. ),
  5752. borderRadius: BorderRadius.circular(16),
  5753. ),
  5754. clipBehavior: Clip.antiAlias,
  5755. child: Padding(
  5756. padding: const EdgeInsets.all(20),
  5757. child: Column(
  5758. crossAxisAlignment: CrossAxisAlignment.start,
  5759. children: [
  5760. // LOGO + 品牌名
  5761. Row(
  5762. children: [
  5763. Image.asset(
  5764. 'assets/images/app_icon.png',
  5765. height: 28,
  5766. width: 28,
  5767. errorBuilder: (_, __, ___) => const SizedBox.shrink(),
  5768. ),
  5769. const SizedBox(width: 8),
  5770. Text(
  5771. 'iBit',
  5772. style: TextStyle(
  5773. color: textPrimary,
  5774. fontSize: 14,
  5775. fontWeight: FontWeight.w700,
  5776. letterSpacing: 0.5),
  5777. ),
  5778. ],
  5779. ),
  5780. const SizedBox(height: 14),
  5781. // 币对 + 永续 tag
  5782. Row(
  5783. children: [
  5784. Text(
  5785. '${coinSymbol}USDT',
  5786. style: TextStyle(
  5787. color: textPrimary,
  5788. fontSize: 22,
  5789. fontWeight: FontWeight.w800),
  5790. ),
  5791. const SizedBox(width: 8),
  5792. Container(
  5793. padding:
  5794. const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
  5795. decoration: BoxDecoration(
  5796. color: const Color(0xFFFFAB00),
  5797. borderRadius: BorderRadius.circular(4),
  5798. ),
  5799. child: Text(AppLocalizations.of(context)!.perpetual,
  5800. style: const TextStyle(
  5801. color: Colors.white,
  5802. fontSize: 11,
  5803. fontWeight: FontWeight.w700)),
  5804. ),
  5805. ],
  5806. ),
  5807. const SizedBox(height: 4),
  5808. // 方向 + 杠杆
  5809. Text(
  5810. '${isLong ? AppLocalizations.of(context)!.openLong : AppLocalizations.of(context)!.openShort} ${pos.leverage.toInt()}X',
  5811. style: TextStyle(
  5812. color: sideColor, fontSize: 15, fontWeight: FontWeight.w700),
  5813. ),
  5814. const SizedBox(height: 14),
  5815. // 收益率(大字)
  5816. Text(AppLocalizations.of(context)!.returnRate,
  5817. style: TextStyle(color: textSecondary, fontSize: 12)),
  5818. const SizedBox(height: 4),
  5819. Text(roeStr,
  5820. style: TextStyle(
  5821. color: pnlColor,
  5822. fontSize: 36,
  5823. fontWeight: FontWeight.w800,
  5824. letterSpacing: -0.5)),
  5825. const SizedBox(height: 16),
  5826. // 最新价 + 开仓均价
  5827. Row(
  5828. children: [
  5829. Expanded(
  5830. child: _ShareDataItem(
  5831. label: AppLocalizations.of(context)!.latestPriceFull,
  5832. value: formatAmount(pos.markPrice),
  5833. textPrimary: textPrimary,
  5834. textSecondary: textSecondary,
  5835. ),
  5836. ),
  5837. Expanded(
  5838. child: _ShareDataItem(
  5839. label: AppLocalizations.of(context)!.openAvgPrice,
  5840. value: formatAmount(pos.entryPrice),
  5841. align: CrossAxisAlignment.end,
  5842. textPrimary: textPrimary,
  5843. textSecondary: textSecondary,
  5844. ),
  5845. ),
  5846. ],
  5847. ),
  5848. const SizedBox(height: 10),
  5849. // 时间
  5850. Text(_formatNow(),
  5851. style: TextStyle(color: textMuted, fontSize: 11)),
  5852. const SizedBox(height: 14),
  5853. // 分隔线
  5854. Divider(color: borderColor, height: 1),
  5855. const SizedBox(height: 14),
  5856. // 邀请码 + 二维码
  5857. Row(
  5858. crossAxisAlignment: CrossAxisAlignment.center,
  5859. children: [
  5860. Expanded(
  5861. child: Column(
  5862. crossAxisAlignment: CrossAxisAlignment.start,
  5863. children: [
  5864. if (inviteCode != null)
  5865. RichText(
  5866. text: TextSpan(
  5867. style: const TextStyle(fontSize: 15),
  5868. children: [
  5869. TextSpan(
  5870. text: AppLocalizations.of(context)!
  5871. .inviteCodeLabel,
  5872. style: TextStyle(color: textSecondary),
  5873. ),
  5874. TextSpan(
  5875. text: inviteCode!,
  5876. style: const TextStyle(
  5877. color: AppColors.brand,
  5878. fontWeight: FontWeight.w700),
  5879. ),
  5880. ],
  5881. ),
  5882. ),
  5883. const SizedBox(height: 4),
  5884. Text(AppLocalizations.of(context)!.registerAndEarnRebate,
  5885. style: TextStyle(color: textMuted, fontSize: 12)),
  5886. ],
  5887. ),
  5888. ),
  5889. Container(
  5890. decoration: BoxDecoration(
  5891. border: Border.all(color: borderColor, width: 1),
  5892. borderRadius: BorderRadius.circular(6),
  5893. ),
  5894. padding: const EdgeInsets.all(4),
  5895. child: qrData != null
  5896. ? QrImageView(
  5897. data: qrData,
  5898. version: QrVersions.auto,
  5899. size: 80,
  5900. eyeStyle: QrEyeStyle(
  5901. eyeShape: QrEyeShape.square,
  5902. color: qrFgColor,
  5903. ),
  5904. dataModuleStyle: QrDataModuleStyle(
  5905. dataModuleShape: QrDataModuleShape.square,
  5906. color: qrFgColor,
  5907. ),
  5908. backgroundColor: qrBgColor,
  5909. errorCorrectionLevel: QrErrorCorrectLevel.M,
  5910. )
  5911. : const SizedBox(width: 80, height: 80),
  5912. ),
  5913. ],
  5914. ),
  5915. ],
  5916. ),
  5917. ),
  5918. );
  5919. }
  5920. }
  5921. class _ShareDataItem extends StatelessWidget {
  5922. const _ShareDataItem({
  5923. required this.label,
  5924. required this.value,
  5925. required this.textPrimary,
  5926. required this.textSecondary,
  5927. this.align = CrossAxisAlignment.start,
  5928. });
  5929. final String label;
  5930. final String value;
  5931. final Color textPrimary;
  5932. final Color textSecondary;
  5933. final CrossAxisAlignment align;
  5934. @override
  5935. Widget build(BuildContext context) {
  5936. return Column(
  5937. crossAxisAlignment: align,
  5938. children: [
  5939. Text(label, style: TextStyle(color: textSecondary, fontSize: 11)),
  5940. const SizedBox(height: 2),
  5941. Text(value,
  5942. style: TextStyle(
  5943. color: textPrimary, fontSize: 13, fontWeight: FontWeight.w600)),
  5944. ],
  5945. );
  5946. }
  5947. }
  5948. // ── 合约骨架屏 ──────────────────────────────────────────────
  5949. /// 持仓/委托 Tab 列表骨架:[rows] 行卡片占位
  5950. class _TabShimmer extends StatelessWidget {
  5951. const _TabShimmer({required this.rows});
  5952. final int rows;
  5953. @override
  5954. Widget build(BuildContext context) {
  5955. return AppShimmer(
  5956. child: Padding(
  5957. padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
  5958. child: Column(
  5959. children: List.generate(
  5960. rows,
  5961. (i) => Padding(
  5962. padding: const EdgeInsets.only(bottom: 12),
  5963. child: Container(
  5964. decoration: BoxDecoration(
  5965. color: Colors.white,
  5966. borderRadius: BorderRadius.circular(8),
  5967. ),
  5968. padding: const EdgeInsets.all(12),
  5969. child: Column(
  5970. crossAxisAlignment: CrossAxisAlignment.start,
  5971. children: [
  5972. // 标题行:币对 + 方向标签 + 浮盈
  5973. Row(children: [
  5974. shimmerBox(80, 14),
  5975. const SizedBox(width: 8),
  5976. shimmerBox(44, 18, radius: 4),
  5977. const Spacer(),
  5978. shimmerBox(70, 14),
  5979. ]),
  5980. const SizedBox(height: 10),
  5981. // 数据行
  5982. Row(children: [
  5983. Expanded(child: shimmerBox(double.infinity, 11)),
  5984. const SizedBox(width: 12),
  5985. Expanded(child: shimmerBox(double.infinity, 11)),
  5986. const SizedBox(width: 12),
  5987. Expanded(child: shimmerBox(double.infinity, 11)),
  5988. ]),
  5989. const SizedBox(height: 8),
  5990. Row(children: [
  5991. Expanded(child: shimmerBox(double.infinity, 11)),
  5992. const SizedBox(width: 12),
  5993. Expanded(child: shimmerBox(double.infinity, 11)),
  5994. const SizedBox(width: 12),
  5995. Expanded(child: shimmerBox(double.infinity, 11)),
  5996. ]),
  5997. const SizedBox(height: 10),
  5998. // 操作按钮行
  5999. Row(children: [
  6000. shimmerBox(56, 24, radius: 4),
  6001. const SizedBox(width: 8),
  6002. shimmerBox(56, 24, radius: 4),
  6003. const SizedBox(width: 8),
  6004. shimmerBox(56, 24, radius: 4),
  6005. ]),
  6006. ],
  6007. ),
  6008. ),
  6009. )),
  6010. ),
  6011. ),
  6012. );
  6013. }
  6014. }
  6015. /// 资产面板骨架
  6016. class _AssetShimmer extends StatelessWidget {
  6017. const _AssetShimmer();
  6018. @override
  6019. Widget build(BuildContext context) {
  6020. return AppShimmer(
  6021. child: Padding(
  6022. padding: const EdgeInsets.all(12),
  6023. child: Column(
  6024. crossAxisAlignment: CrossAxisAlignment.start,
  6025. children: [
  6026. shimmerBox(100, 12),
  6027. const SizedBox(height: 8),
  6028. shimmerBox(160, 26),
  6029. const SizedBox(height: 14),
  6030. Row(children: [
  6031. Expanded(
  6032. child: Column(
  6033. crossAxisAlignment: CrossAxisAlignment.start,
  6034. children: [
  6035. shimmerBox(60, 11),
  6036. const SizedBox(height: 6),
  6037. shimmerBox(80, 14),
  6038. ])),
  6039. Expanded(
  6040. child: Column(
  6041. crossAxisAlignment: CrossAxisAlignment.start,
  6042. children: [
  6043. shimmerBox(60, 11),
  6044. const SizedBox(height: 6),
  6045. shimmerBox(80, 14),
  6046. ])),
  6047. Expanded(
  6048. child: Column(
  6049. crossAxisAlignment: CrossAxisAlignment.start,
  6050. children: [
  6051. shimmerBox(60, 11),
  6052. const SizedBox(height: 6),
  6053. shimmerBox(80, 14),
  6054. ])),
  6055. ]),
  6056. ],
  6057. ),
  6058. ),
  6059. );
  6060. }
  6061. }
  6062. class _FuturesShimmer extends StatelessWidget {
  6063. const _FuturesShimmer();
  6064. @override
  6065. Widget build(BuildContext context) {
  6066. return AppShimmer(
  6067. child: SingleChildScrollView(
  6068. physics: const NeverScrollableScrollPhysics(),
  6069. child: Column(
  6070. children: [
  6071. // 上半:左侧下单区 + 右侧盘口
  6072. SizedBox(
  6073. height: 400,
  6074. child: Row(
  6075. crossAxisAlignment: CrossAxisAlignment.stretch,
  6076. children: [
  6077. // 左侧下单区骨架
  6078. Expanded(
  6079. flex: 55,
  6080. child: Padding(
  6081. padding: const EdgeInsets.all(12),
  6082. child: Column(
  6083. crossAxisAlignment: CrossAxisAlignment.start,
  6084. children: [
  6085. // 开多/开空 tab
  6086. Row(children: [
  6087. shimmerBox(70, 30, radius: 6),
  6088. const SizedBox(width: 8),
  6089. shimmerBox(70, 30, radius: 6),
  6090. ]),
  6091. const SizedBox(height: 12),
  6092. // 价格输入框
  6093. shimmerFill(44, radius: 8),
  6094. const SizedBox(height: 10),
  6095. // 数量输入框
  6096. shimmerFill(44, radius: 8),
  6097. const SizedBox(height: 10),
  6098. // 滑块
  6099. shimmerFill(20, radius: 10),
  6100. const SizedBox(height: 16),
  6101. // 按钮
  6102. Row(children: [
  6103. Expanded(child: shimmerFill(40, radius: 8)),
  6104. const SizedBox(width: 8),
  6105. Expanded(child: shimmerFill(40, radius: 8)),
  6106. ]),
  6107. const SizedBox(height: 16),
  6108. // 数据行
  6109. ...List.generate(
  6110. 3,
  6111. (_) => Padding(
  6112. padding: const EdgeInsets.only(bottom: 8),
  6113. child: Row(
  6114. mainAxisAlignment:
  6115. MainAxisAlignment.spaceBetween,
  6116. children: [
  6117. shimmerBox(60, 11),
  6118. shimmerBox(70, 11),
  6119. ],
  6120. ),
  6121. )),
  6122. ],
  6123. ),
  6124. ),
  6125. ),
  6126. // 右侧盘口骨架
  6127. Expanded(
  6128. flex: 45,
  6129. child: Padding(
  6130. padding: const EdgeInsets.symmetric(
  6131. horizontal: 8, vertical: 12),
  6132. child: Column(
  6133. children: [
  6134. // 盘口 header
  6135. Row(
  6136. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  6137. children: [
  6138. shimmerBox(40, 11),
  6139. shimmerBox(60, 11),
  6140. shimmerBox(40, 11),
  6141. ],
  6142. ),
  6143. const SizedBox(height: 8),
  6144. // 盘口行
  6145. ...List.generate(
  6146. 12,
  6147. (_) => Padding(
  6148. padding:
  6149. const EdgeInsets.symmetric(vertical: 4),
  6150. child: Row(
  6151. children: [
  6152. Expanded(
  6153. child: shimmerBox(
  6154. double.infinity, 11)),
  6155. const SizedBox(width: 6),
  6156. Expanded(
  6157. child: shimmerBox(
  6158. double.infinity, 11)),
  6159. ],
  6160. ),
  6161. )),
  6162. ],
  6163. ),
  6164. ),
  6165. ),
  6166. ],
  6167. ),
  6168. ),
  6169. // 下半:持仓/委托区
  6170. Padding(
  6171. padding: const EdgeInsets.all(12),
  6172. child: Column(
  6173. crossAxisAlignment: CrossAxisAlignment.start,
  6174. children: [
  6175. // tab 行
  6176. Row(children: [
  6177. shimmerBox(60, 28, radius: 6),
  6178. const SizedBox(width: 8),
  6179. shimmerBox(60, 28, radius: 6),
  6180. const SizedBox(width: 8),
  6181. shimmerBox(60, 28, radius: 6),
  6182. ]),
  6183. const SizedBox(height: 16),
  6184. // 空状态占位
  6185. Center(child: shimmerBox(120, 14)),
  6186. ],
  6187. ),
  6188. ),
  6189. ],
  6190. ),
  6191. ),
  6192. );
  6193. }
  6194. }
  6195. /// 测量子组件渲染高度,每帧变化时回调。
  6196. class _SizeReporter extends StatefulWidget {
  6197. const _SizeReporter({required this.child, required this.onHeight});
  6198. final Widget child;
  6199. final ValueChanged<double> onHeight;
  6200. @override
  6201. State<_SizeReporter> createState() => _SizeReporterState();
  6202. }
  6203. class _SizeReporterState extends State<_SizeReporter> {
  6204. double? _lastHeight;
  6205. @override
  6206. Widget build(BuildContext context) {
  6207. WidgetsBinding.instance.addPostFrameCallback((_) {
  6208. if (!mounted) return;
  6209. final rb = context.findRenderObject() as RenderBox?;
  6210. if (rb == null || !rb.hasSize) return;
  6211. final h = rb.size.height;
  6212. if (h != _lastHeight) {
  6213. _lastHeight = h;
  6214. widget.onHeight(h);
  6215. }
  6216. });
  6217. return widget.child;
  6218. }
  6219. }